BEGIN;

-- Drop new indexes and FK
DROP INDEX IF EXISTS idx_product_warehouses_project_flock_kandang_id;
DROP INDEX IF EXISTS idx_product_warehouses_unique;

ALTER TABLE product_warehouses
    DROP CONSTRAINT IF EXISTS fk_product_warehouses_project_flock_kandang_id,
    ALTER COLUMN project_flock_kandang_id DROP NOT NULL,
    DROP COLUMN IF EXISTS project_flock_kandang_id;

-- Revert qty to integer quantity
ALTER TABLE product_warehouses
    RENAME COLUMN qty TO quantity;

ALTER TABLE product_warehouses
    ALTER COLUMN quantity TYPE INTEGER USING quantity::integer,
    ALTER COLUMN quantity SET DEFAULT 0,
    ALTER COLUMN quantity SET NOT NULL;

-- Restore audit/soft-delete columns
ALTER TABLE product_warehouses
    ADD COLUMN IF NOT EXISTS created_by BIGINT REFERENCES users (id),
    ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(),
    ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ DEFAULT NOW(),
    ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;

-- Recreate prior indexes
CREATE INDEX IF NOT EXISTS idx_product_warehouses_deleted_at ON product_warehouses (deleted_at);

CREATE UNIQUE INDEX IF NOT EXISTS idx_product_warehouses_unique
    ON product_warehouses (product_id, warehouse_id)
    WHERE deleted_at IS NULL;

COMMIT;
