CREATE TABLE IF NOT EXISTS laying_kandang_transfers (
    id BIGSERIAL PRIMARY KEY,
    kandang_id BIGINT,
    product_warehouse_id BIGINT,
    qty NUMERIC(15,3),
    laying_transfer_id BIGINT NOT NULL
);

-- FOREIGN KEYS (dijalankan setelah semua tabel parent ada)
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'kandangs') THEN
        ALTER TABLE laying_kandang_transfers
            ADD CONSTRAINT fk_laying_kandang_transfers_kandang
            FOREIGN KEY (kandang_id)
            REFERENCES kandangs(id)
            ON DELETE RESTRICT ON UPDATE CASCADE;
    END IF;

    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'product_warehouses') THEN
        ALTER TABLE laying_kandang_transfers
            ADD CONSTRAINT fk_laying_kandang_transfers_product_warehouse
            FOREIGN KEY (product_warehouse_id)
            REFERENCES product_warehouses(id)
            ON DELETE RESTRICT ON UPDATE CASCADE;
    END IF;

    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'laying_transfers') THEN
        ALTER TABLE laying_kandang_transfers
            ADD CONSTRAINT fk_laying_kandang_transfers_laying_transfer
            FOREIGN KEY (laying_transfer_id)
            REFERENCES laying_transfers(id)
            ON DELETE RESTRICT ON UPDATE CASCADE;
    END IF;
END $$;

-- INDEXES
CREATE INDEX IF NOT EXISTS idx_laying_kandang_transfers_kandang_id ON laying_kandang_transfers(kandang_id);
CREATE INDEX IF NOT EXISTS idx_laying_kandang_transfers_product_warehouse_id ON laying_kandang_transfers(product_warehouse_id);
CREATE INDEX IF NOT EXISTS idx_laying_kandang_transfers_laying_transfer_id ON laying_kandang_transfers(laying_transfer_id);