-- Active home/away kits for a club. Ownership remains the generic owned_cards
-- inventory; this table only records which owned instances occupy the two kit
-- roles. FIFA-specific resource ids and wire shapes stay in the FIFA17 adapter.
CREATE TABLE IF NOT EXISTS club_kit_assignments (
    club_id      TEXT NOT NULL REFERENCES clubs(id) ON DELETE CASCADE,
    slot         TEXT NOT NULL CHECK (slot IN ('home', 'away')),
    owned_card_id TEXT NOT NULL UNIQUE REFERENCES owned_cards(id) ON DELETE CASCADE,
    updated_at   TEXT NOT NULL,
    PRIMARY KEY (club_id, slot)
);

CREATE INDEX IF NOT EXISTS idx_club_kit_assignments_owned
    ON club_kit_assignments(owned_card_id);

-- Market transfers change owned_cards.club_id by UPDATE rather than DELETE.
-- Remove any old-club active designation before ownership moves so a stale row
-- cannot hide or block the item for its new owner.
CREATE TRIGGER IF NOT EXISTS clear_club_kit_assignment_before_transfer
BEFORE UPDATE OF club_id ON owned_cards
WHEN OLD.club_id <> NEW.club_id
BEGIN
    DELETE FROM club_kit_assignments WHERE owned_card_id = OLD.id;
END;
