BEGIN;

-- Recreate legacy columns on project_flock_kandangs
DROP INDEX IF EXISTS idx_project_flock_kandangs_unique;

ALTER TABLE project_flock_kandangs
    ADD COLUMN IF NOT EXISTS created_by BIGINT REFERENCES users (id) ON DELETE SET NULL ON UPDATE CASCADE,
    ADD COLUMN IF NOT EXISTS assigned_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    ADD COLUMN IF NOT EXISTS detached_at TIMESTAMPTZ,
    ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW();

CREATE UNIQUE INDEX IF NOT EXISTS idx_project_flock_kandangs_active
    ON project_flock_kandangs (project_flock_id, kandang_id)
    WHERE detached_at IS NULL;

-- Restore product_category_id reference and drop category column
ALTER TABLE project_flocks
    ADD COLUMN IF NOT EXISTS product_category_id BIGINT REFERENCES product_categories (id) ON DELETE RESTRICT ON UPDATE CASCADE;

ALTER TABLE project_flocks
    DROP COLUMN IF EXISTS category;

COMMIT;

DROP INDEX IF EXISTS project_flocks_flock_period_unique;
