BEGIN;

-- Add category column to project_flocks and backfill existing rows
ALTER TABLE project_flocks
    ADD COLUMN IF NOT EXISTS category VARCHAR(20);

UPDATE project_flocks
SET category = 'GROWING'
WHERE category IS NULL;

ALTER TABLE project_flocks
    ALTER COLUMN category SET NOT NULL;

ALTER TABLE project_flocks
    ALTER COLUMN category SET DEFAULT 'GROWING';

-- Drop legacy foreign key reference and column
ALTER TABLE project_flocks
    DROP CONSTRAINT IF EXISTS project_flocks_product_category_id_fkey;

ALTER TABLE project_flocks
    DROP COLUMN IF EXISTS product_category_id;

-- Simplify project_flock_kandangs structure
DROP INDEX IF EXISTS idx_project_flock_kandangs_active;

ALTER TABLE project_flock_kandangs
    DROP COLUMN IF EXISTS created_by,
    DROP COLUMN IF EXISTS assigned_at,
    DROP COLUMN IF EXISTS detached_at,
    DROP COLUMN IF EXISTS updated_at;

ALTER TABLE project_flock_kandangs
    ALTER COLUMN created_at SET DEFAULT NOW();

CREATE UNIQUE INDEX IF NOT EXISTS idx_project_flock_kandangs_unique
    ON project_flock_kandangs (project_flock_id, kandang_id);

COMMIT;

CREATE UNIQUE INDEX project_flocks_flock_period_unique
ON project_flocks (flock_id, period)
WHERE deleted_at IS NULL;
