-- t-paliad-243: drafts may exist without a project attached.
--
-- The global /submissions/new picker lets a lawyer start a Schriftsatz
-- draft straight from the top-level Schriftsätze sidebar, with or
-- without binding it to a project. project_id therefore becomes
-- optional. Existing rows are unaffected; new rows may insert NULL.
--
-- RLS rewrite: every policy splits on (project_id IS NULL):
--
--   project_id IS NOT NULL → gate on paliad.can_see_project (existing
--                            inheritance-aware visibility).
--   project_id IS NULL     → owner-only (user_id = auth.uid()). A
--                            project-less draft is a personal scratch
--                            space — never shared, never visible to
--                            other team members.
--
-- INSERT enforces the same shape via WITH CHECK: a project-less insert
-- only writes user_id = auth.uid(); a project-scoped insert additionally
-- requires can_see_project.

ALTER TABLE paliad.submission_drafts
    ALTER COLUMN project_id DROP NOT NULL;

DROP POLICY IF EXISTS submission_drafts_select ON paliad.submission_drafts;
CREATE POLICY submission_drafts_select
    ON paliad.submission_drafts FOR SELECT TO authenticated
    USING (
        (project_id IS NULL AND user_id = auth.uid())
        OR (project_id IS NOT NULL AND paliad.can_see_project(project_id))
    );

DROP POLICY IF EXISTS submission_drafts_insert ON paliad.submission_drafts;
CREATE POLICY submission_drafts_insert
    ON paliad.submission_drafts FOR INSERT TO authenticated
    WITH CHECK (
        user_id = auth.uid()
        AND (
            project_id IS NULL
            OR paliad.can_see_project(project_id)
        )
    );

DROP POLICY IF EXISTS submission_drafts_update ON paliad.submission_drafts;
CREATE POLICY submission_drafts_update
    ON paliad.submission_drafts FOR UPDATE TO authenticated
    USING (
        user_id = auth.uid()
        AND (
            project_id IS NULL
            OR paliad.can_see_project(project_id)
        )
    )
    WITH CHECK (
        user_id = auth.uid()
        AND (
            project_id IS NULL
            OR paliad.can_see_project(project_id)
        )
    );

DROP POLICY IF EXISTS submission_drafts_delete ON paliad.submission_drafts;
CREATE POLICY submission_drafts_delete
    ON paliad.submission_drafts FOR DELETE TO authenticated
    USING (
        user_id = auth.uid()
        AND (
            project_id IS NULL
            OR paliad.can_see_project(project_id)
        )
    );
