-- =====================================================================
--  TeeCup — Bingo Bango Bongo (org individuell turnering), migrasjon 044.
--  Samme begrunnelse som 043 (frittstående runder) -- se den migrasjonens
--  header. Denne dekker den parallelle, RLS-beskyttede org-modellen
--  (ADR-037): tournament.scoring_method='bingo_bango_bongo' + en ny
--  dedikert tabell tournament_round_bbb_hole (samme composite-FK-/RLS-
--  mønster som resten av migrasjon 040).
-- =====================================================================
\set ON_ERROR_STOP on

ALTER TABLE tournament DROP CONSTRAINT tournament_scoring_method_check;
ALTER TABLE tournament ADD CONSTRAINT tournament_scoring_method_check
    CHECK (scoring_method IS NULL OR scoring_method IN ('stroke_gross', 'stroke_net', 'stableford', 'copenhagen', 'bingo_bango_bongo'));

ALTER TABLE tournament ADD COLUMN bbb_sweep_bonus_enabled boolean NOT NULL DEFAULT false;

-- Cachet totalsum per deltaker per runde (samme mønster som gross_total/
-- net_total/stableford_points/copenhagen_points -- SQL summerer bare det
-- cachede ved lesing i leaderboardet, motoren regner på nytt ved hver
-- hull-innsending).
ALTER TABLE tournament_round_score ADD COLUMN bbb_points smallint;

CREATE TABLE tournament_round_bbb_hole (
    id                    uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    organization_id       uuid NOT NULL,
    tournament_round_id   uuid NOT NULL,
    hole_number           smallint NOT NULL CHECK (hole_number BETWEEN 1 AND 18),
    bingo_participant_id  uuid,
    bango_participant_id  uuid,
    bongo_participant_id  uuid,
    FOREIGN KEY (organization_id, tournament_round_id)
        REFERENCES tournament_round(organization_id, id) ON DELETE CASCADE,
    FOREIGN KEY (organization_id, bingo_participant_id)
        REFERENCES tournament_participant(organization_id, id) ON DELETE SET NULL,
    FOREIGN KEY (organization_id, bango_participant_id)
        REFERENCES tournament_participant(organization_id, id) ON DELETE SET NULL,
    FOREIGN KEY (organization_id, bongo_participant_id)
        REFERENCES tournament_participant(organization_id, id) ON DELETE SET NULL,
    UNIQUE (tournament_round_id, hole_number)
);

GRANT SELECT, INSERT, UPDATE, DELETE ON tournament_round_bbb_hole TO teecup_app;

ALTER TABLE tournament_round_bbb_hole ENABLE ROW LEVEL SECURITY;
ALTER TABLE tournament_round_bbb_hole FORCE  ROW LEVEL SECURITY;
CREATE POLICY org_isolation ON tournament_round_bbb_hole
    USING       (organization_id = current_setting('app.current_org', true)::uuid)
    WITH CHECK  (organization_id = current_setting('app.current_org', true)::uuid);
