local Save = {}

-- Creates a new sub-collection inside targetSet, adds the two photos
-- in left → right order.
--
-- Naming: simple `Pair NNNN` (zero-padded for sortable order).
-- Earlier builds (≤101) encoded `L:<leftname> R:<rightname>` in the
-- name as a "which side was which" record.  Dropped because:
--   1. LR's collection sidebar truncates long names — even at max
--      width the right side just shows "R…" so the encoding's
--      identification benefit didn't actually work.
--   2. LR's inline-rename text field wraps for long names, breaking
--      the rename UX.
--   3. Net visual noise in the sidebar.
--
-- L → R display order in the saved sub-collection relies on LR's
-- "Custom Order: Ascending" sort.  macOS LR uses Custom Order as
-- the default for new collections (we add left then right; LR
-- displays in that order).  Windows LR defaults to Capture Time,
-- which can flip pairs whose photos were captured in non-L-to-R
-- order — Windows users need to set the saved collection's sort
-- to "Custom Order: Ascending" to see the original layout.
-- Documented in README + first-save in-app tip.
--
-- catalog: LrCatalog
-- targetSet: LrCollectionSet
-- pair: { left = LrPhoto, right = LrPhoto }
-- pairNumber: integer (already incremented before calling)
--
-- Returns the new LrCollection.
function Save.savePair(catalog, targetSet, pair, pairNumber)
    if not targetSet then
        error('Save.savePair: target collection set is required')
    end

    -- "Saved Random Pair NNNN" — the "Random" word ties the
    -- collection name back to the plugin (Random Pair Generator)
    -- so a user looking at the collection later, possibly long
    -- after they last opened the plugin, can connect the saved
    -- pair to where it came from.  Zero-padded NNNN keeps the
    -- list sortable in LR's collection sidebar (collections
    -- sort alphabetically; 4-digit padding holds order up to
    -- 9999 saves per target set).
    local name = string.format('Saved Random Pair %04d', pairNumber)

    local newCollection
    catalog:withWriteAccessDo('Save Pair ' .. tostring(pairNumber), function()
        newCollection = catalog:createCollection(name, targetSet, true)
        newCollection:addPhotos({ pair.left, pair.right })
        -- Insertion order is left, right.  Display order in LR
        -- depends on the collection's sort method (Custom Order
        -- preserves insertion).  See ideas/decision-support.md
        -- "Custom sort order on saved pair collections."
    end)

    return newCollection
end

return Save
