-- Collaboration + shared cross-off ("claim") support.

-- Per-list toggle: may anonymous holders of the share link cross items off?
ALTER TABLE lists ADD COLUMN allow_guest_crossoff BOOLEAN NOT NULL DEFAULT false;

-- Shared claim on an item: who crossed it off, and when. Visible to everyone
-- who can see the list (gift-registry "this one's taken" semantics).
ALTER TABLE items ADD COLUMN claimed_at         TIMESTAMPTZ;
ALTER TABLE items ADD COLUMN claimed_by_user_id UUID REFERENCES users(id) ON DELETE SET NULL;
ALTER TABLE items ADD COLUMN claimed_by_name    TEXT;

-- Collaboration invite links. Each link carries the role it grants; revoking
-- a link is just deleting the row. Accepting one creates a collaborator.
CREATE TABLE list_invites (
    id         UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    list_id    UUID NOT NULL REFERENCES lists(id) ON DELETE CASCADE,
    token      TEXT NOT NULL UNIQUE,
    role       TEXT NOT NULL CHECK (role IN ('editor', 'crosser')),
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX list_invites_list ON list_invites (list_id);

-- Accepted collaborators on a list (besides the owner).
CREATE TABLE list_collaborators (
    list_id    UUID NOT NULL REFERENCES lists(id) ON DELETE CASCADE,
    user_id    UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    role       TEXT NOT NULL CHECK (role IN ('editor', 'crosser')),
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (list_id, user_id)
);
CREATE INDEX list_collaborators_user ON list_collaborators (user_id);
