BEGIN;

-- Drop indexes that depend on deleted_at or old uniqueness
DROP INDEX IF EXISTS idx_product_warehouses_deleted_at;
DROP INDEX IF EXISTS idx_product_warehouses_unique;

-- Add new relation and adjust quantity column
ALTER TABLE product_warehouses
    ADD COLUMN IF NOT EXISTS project_flock_kandang_id BIGINT;

ALTER TABLE product_warehouses
    RENAME COLUMN quantity TO qty;

-- Enforce numeric quantity with precision and default
ALTER TABLE product_warehouses
    ALTER COLUMN qty TYPE NUMERIC(15, 3) USING qty::numeric(15, 3),
    ALTER COLUMN qty SET DEFAULT 0,
    ALTER COLUMN qty SET NOT NULL;

-- Remove audit/soft-delete columns no longer used
ALTER TABLE product_warehouses
    DROP COLUMN IF EXISTS created_by,
    DROP COLUMN IF EXISTS created_at,
    DROP COLUMN IF EXISTS updated_at,
    DROP COLUMN IF EXISTS deleted_at;

-- Enforce FK and not-null for project_flock_kandang_id
ALTER TABLE product_warehouses
    ADD CONSTRAINT fk_product_warehouses_project_flock_kandang_id
        FOREIGN KEY (project_flock_kandang_id)
        REFERENCES project_flock_kandangs (id)
        ON DELETE RESTRICT ON UPDATE CASCADE;

-- New indexes
CREATE INDEX IF NOT EXISTS idx_product_warehouses_project_flock_kandang_id
    ON product_warehouses (project_flock_kandang_id);

CREATE UNIQUE INDEX IF NOT EXISTS idx_product_warehouses_unique
    ON product_warehouses (product_id, warehouse_id, project_flock_kandang_id);

COMMIT;
