BEGIN;

DO $$
DECLARE
    fallback_fcr_id BIGINT;
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_schema = 'public'
          AND table_name = 'project_flocks'
          AND column_name = 'fcr_id'
    ) THEN
        ALTER TABLE project_flocks
            ADD COLUMN fcr_id BIGINT;
    END IF;

    SELECT id INTO fallback_fcr_id
    FROM fcrs
    ORDER BY id ASC
    LIMIT 1;

    IF fallback_fcr_id IS NOT NULL THEN
        UPDATE project_flocks
        SET fcr_id = fallback_fcr_id
        WHERE fcr_id IS NULL;

        ALTER TABLE project_flocks
            ALTER COLUMN fcr_id SET NOT NULL;
    END IF;

    IF EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'project_flocks_fcr_id_fkey'
    ) THEN
        ALTER TABLE project_flocks
            DROP CONSTRAINT project_flocks_fcr_id_fkey;
    END IF;

    ALTER TABLE project_flocks
        ADD CONSTRAINT project_flocks_fcr_id_fkey
        FOREIGN KEY (fcr_id) REFERENCES fcrs(id)
        ON DELETE RESTRICT ON UPDATE CASCADE;
END $$;

COMMIT;
