CREATE TABLE expenses (
    id BIGSERIAL PRIMARY KEY,
    reference_number VARCHAR(50) UNIQUE NOT NULL,
    supplier_id BIGINT NULL,
    category VARCHAR(50) NOT NULL CHECK (
        category IN ('BOP', 'NON-BOP')
    ),
    po_number VARCHAR(50) NULL,
    document_path JSON,
    expense_date DATE NOT NULL,
    grand_total NUMERIC(15, 3) DEFAULT 0,
    note TEXT,
    created_by BIGINT,
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now(),
    deleted_at TIMESTAMPTZ
);

CREATE SEQUENCE expenses_ref_seq INCREMENT BY 1 START WITH 1;

-- Tambahkan Foreign Key ke suppliers
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'suppliers') THEN
        ALTER TABLE expenses
            ADD CONSTRAINT fk_expenses_supplier_id 
            FOREIGN KEY (supplier_id) REFERENCES suppliers(id);

END IF;

END $$;

-- Tambahkan Foreign Key ke users (created_by)
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'users') THEN
        ALTER TABLE expenses
            ADD CONSTRAINT fk_expenses_created_by
            FOREIGN KEY (created_by) REFERENCES users(id);
    END IF;
END $$;

-- Index
CREATE INDEX idx_expenses_supplier_id ON expenses (supplier_id);

CREATE INDEX idx_expenses_expense_date ON expenses (expense_date);

CREATE INDEX idx_expenses_deleted_at ON expenses (deleted_at);