BEGIN;

ALTER TABLE recording_depletions
    ADD COLUMN IF NOT EXISTS source_project_flock_kandang_id BIGINT NULL;

ALTER TABLE recording_eggs
    ADD COLUMN IF NOT EXISTS project_flock_kandang_id BIGINT NULL;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'fk_recording_depletions_source_project_flock_kandang_id'
    ) THEN
        ALTER TABLE recording_depletions
            ADD CONSTRAINT fk_recording_depletions_source_project_flock_kandang_id
            FOREIGN KEY (source_project_flock_kandang_id)
            REFERENCES project_flock_kandangs(id)
            ON DELETE SET NULL
            ON UPDATE CASCADE;
    END IF;
END $$;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'fk_recording_eggs_project_flock_kandang_id'
    ) THEN
        ALTER TABLE recording_eggs
            ADD CONSTRAINT fk_recording_eggs_project_flock_kandang_id
            FOREIGN KEY (project_flock_kandang_id)
            REFERENCES project_flock_kandangs(id)
            ON DELETE SET NULL
            ON UPDATE CASCADE;
    END IF;
END $$;

CREATE INDEX IF NOT EXISTS idx_recording_depletions_source_project_flock_kandang_id
    ON recording_depletions(source_project_flock_kandang_id);

CREATE INDEX IF NOT EXISTS idx_recording_eggs_project_flock_kandang_id
    ON recording_eggs(project_flock_kandang_id);

UPDATE recording_depletions rd
SET source_project_flock_kandang_id = r.project_flock_kandangs_id
FROM recordings r
WHERE r.id = rd.recording_id
  AND rd.source_project_flock_kandang_id IS NULL
  AND r.project_flock_kandangs_id IS NOT NULL;

UPDATE recording_eggs re
SET project_flock_kandang_id = r.project_flock_kandangs_id
FROM recordings r
WHERE r.id = re.recording_id
  AND re.project_flock_kandang_id IS NULL
  AND r.project_flock_kandangs_id IS NOT NULL;

COMMIT;
