-- ===============================================================
--  STOCK TRANSFERS (HEADER)
-- ===============================================================

CREATE SEQUENCE IF NOT EXISTS stock_transfer_seq START 1;

CREATE TABLE IF NOT EXISTS stock_transfers (
    id BIGSERIAL PRIMARY KEY,
    movement_number VARCHAR(50) UNIQUE NOT NULL,
    from_warehouse_id BIGINT NOT NULL,
    to_warehouse_id BIGINT NOT NULL,
    area_id BIGINT,
    reason TEXT,
    transfer_date DATE NOT NULL,
    created_by BIGINT,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    deleted_at TIMESTAMPTZ
);

-- FOREIGN KEYS (dijalankan setelah semua tabel parent ada)
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'warehouses') THEN
        ALTER TABLE stock_transfers
            ADD CONSTRAINT fk_stock_transfers_from_warehouse
            FOREIGN KEY (from_warehouse_id)
            REFERENCES warehouses(id)
            ON DELETE RESTRICT ON UPDATE CASCADE;
        ALTER TABLE stock_transfers
            ADD CONSTRAINT fk_stock_transfers_to_warehouse
            FOREIGN KEY (to_warehouse_id)
            REFERENCES warehouses(id)
            ON DELETE RESTRICT ON UPDATE CASCADE;
    END IF;

    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'areas') THEN
        ALTER TABLE stock_transfers
            ADD CONSTRAINT fk_stock_transfers_area
            FOREIGN KEY (area_id)
            REFERENCES areas(id)
            ON DELETE SET NULL ON UPDATE CASCADE;
    END IF;

    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'users') THEN
        ALTER TABLE stock_transfers
            ADD CONSTRAINT fk_stock_transfers_created_by
            FOREIGN KEY (created_by)
            REFERENCES users(id)
            ON DELETE SET NULL ON UPDATE CASCADE;
    END IF;
END $$;

-- INDEXES
CREATE INDEX IF NOT EXISTS idx_stock_transfers_from_warehouse_id ON stock_transfers(from_warehouse_id);
CREATE INDEX IF NOT EXISTS idx_stock_transfers_to_warehouse_id   ON stock_transfers(to_warehouse_id);
CREATE INDEX IF NOT EXISTS idx_stock_transfers_transfer_date     ON stock_transfers(transfer_date);
