-- t-paliad-243 revert: restore NOT NULL on project_id.
--
-- The revert refuses to run if any project-less draft exists — those
-- rows would silently fail the NOT NULL re-imposition and corrupt the
-- migration runner's state. The safe revert path is to surface the
-- conflict to the operator who can decide whether to attach the rows
-- to a project or delete them before retrying the down.

DO $$
BEGIN
    IF EXISTS (
        SELECT 1 FROM paliad.submission_drafts WHERE project_id IS NULL
    ) THEN
        RAISE EXCEPTION
            'cannot re-impose NOT NULL on paliad.submission_drafts.project_id: '
            'project-less drafts exist. Attach them to a project or delete '
            'them, then re-run the down migration.';
    END IF;
END $$;

ALTER TABLE paliad.submission_drafts
    ALTER COLUMN project_id SET 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 (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 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 paliad.can_see_project(project_id))
    WITH CHECK (user_id = auth.uid() AND 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 paliad.can_see_project(project_id));
