BEGIN;

DO $$
BEGIN
    IF EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'fk_project_flock_kandang_uniformity_project_flock_kandang'
    ) THEN
        ALTER TABLE project_flock_kandang_uniformity
            DROP CONSTRAINT fk_project_flock_kandang_uniformity_project_flock_kandang;
    END IF;
END $$;

ALTER TABLE project_flock_kandang_uniformity
    ADD CONSTRAINT fk_project_flock_kandang_uniformity_project_flock_kandang
        FOREIGN KEY (project_flock_kandang_id)
        REFERENCES project_flock_kandangs (id)
        ON DELETE CASCADE ON UPDATE CASCADE;

DO $$
BEGIN
    IF EXISTS (
        SELECT 1
        FROM pg_tables
        WHERE tablename = 'project_budgets'
    ) THEN
        IF EXISTS (
            SELECT 1
            FROM pg_constraint
            WHERE conname = 'fk_project_budgets_project_flock_id'
        ) THEN
            ALTER TABLE project_budgets
                DROP CONSTRAINT fk_project_budgets_project_flock_id;
        END IF;

        ALTER TABLE project_budgets
            ADD CONSTRAINT fk_project_budgets_project_flock_id
            FOREIGN KEY (project_flock_id)
            REFERENCES project_flocks(id)
            ON DELETE CASCADE ON UPDATE CASCADE;
    END IF;
END $$;

DO $$
BEGIN
    IF EXISTS (
        SELECT 1
        FROM pg_trigger
        WHERE tgname = 'trg_soft_delete_fk_project_flock_kandang_uniformity'
    ) THEN
        DROP TRIGGER trg_soft_delete_fk_project_flock_kandang_uniformity
        ON project_flock_kandang_uniformity;
    END IF;

    IF EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_schema = 'public'
          AND table_name = 'project_flock_kandang_uniformity'
          AND column_name = 'created_at'
    ) THEN
        ALTER TABLE project_flock_kandang_uniformity
            DROP COLUMN created_at;
    END IF;

    IF EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_schema = 'public'
          AND table_name = 'project_flock_kandang_uniformity'
          AND column_name = 'updated_at'
    ) THEN
        ALTER TABLE project_flock_kandang_uniformity
            DROP COLUMN updated_at;
    END IF;

    IF EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_schema = 'public'
          AND table_name = 'project_flock_kandang_uniformity'
          AND column_name = 'deleted_at'
    ) THEN
        ALTER TABLE project_flock_kandang_uniformity
            DROP COLUMN deleted_at;
    END IF;
END $$;

COMMIT;
