-- ===============================================================
--  STOCK TRANSFER DETAILS (PRODUK)
-- ===============================================================

CREATE TABLE IF NOT EXISTS stock_transfer_details (
    id BIGSERIAL PRIMARY KEY,
    stock_transfer_id BIGINT NOT NULL,
    product_id BIGINT NOT NULL,
    quantity NUMERIC(15, 3) NOT NULL CHECK (quantity > 0),
    before_quantity NUMERIC(15, 3),
    after_quantity NUMERIC(15, 3),
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    deleted_at TIMESTAMPTZ
);

-- ===============================================================
--  FOREIGN KEYS (dengan pengecekan tabel agar anti gagal)
-- ===============================================================

DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'stock_transfers') THEN
        EXECUTE
        'ALTER TABLE stock_transfer_details
         ADD CONSTRAINT fk_stock_transfer_details_transfer
         FOREIGN KEY (stock_transfer_id)
         REFERENCES stock_transfers(id)
         ON DELETE CASCADE ON UPDATE CASCADE';
    END IF;

    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'products') THEN
        EXECUTE
        'ALTER TABLE stock_transfer_details
         ADD CONSTRAINT fk_stock_transfer_details_product
         FOREIGN KEY (product_id)
         REFERENCES products(id)
         ON DELETE RESTRICT ON UPDATE CASCADE';
    END IF;
END $$;

-- ===============================================================
--  INDEXES
-- ===============================================================

CREATE INDEX IF NOT EXISTS idx_stock_transfer_details_transfer_id ON stock_transfer_details (stock_transfer_id);

CREATE INDEX IF NOT EXISTS idx_stock_transfer_details_product_id ON stock_transfer_details (product_id);