CREATE TABLE IF NOT EXISTS purchases (
    id BIGSERIAL PRIMARY KEY,
    pr_number VARCHAR NOT NULL,
    po_number VARCHAR NULL,
    po_date TIMESTAMPTZ NULL,
    supplier_id BIGINT NOT NULL,
    credit_term INT NOT NULL,
    due_date TIMESTAMPTZ,
    grand_total NUMERIC(15, 3) NOT NULL,
    notes TEXT,
    created_at TIMESTAMPTZ NOT NULL,
    updated_at TIMESTAMPTZ NOT NULL,
    deleted_at TIMESTAMPTZ,
    created_by BIGINT NOT NULL,
    CONSTRAINT uq_purchases_pr_number UNIQUE (pr_number),
    CONSTRAINT uq_purchases_po_number UNIQUE (po_number)
);

DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'suppliers') THEN
        EXECUTE
        'ALTER TABLE purchases
         ADD CONSTRAINT fk_purchases_supplier
         FOREIGN KEY (supplier_id)
         REFERENCES suppliers(id)
         ON DELETE RESTRICT ON UPDATE CASCADE';
    END IF;

    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'users') THEN
        EXECUTE
        'ALTER TABLE purchases
         ADD CONSTRAINT fk_purchases_created_by
         FOREIGN KEY (created_by)
         REFERENCES users(id)
         ON DELETE RESTRICT ON UPDATE CASCADE';
    END IF;

    IF EXISTS (
        SELECT 1 FROM pg_tables WHERE tablename = 'purchase_items'
    ) AND NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'fk_purchase_items_purchase'
    ) THEN
        EXECUTE
        'ALTER TABLE purchase_items
         ADD CONSTRAINT fk_purchase_items_purchase
         FOREIGN KEY (purchase_id)
         REFERENCES purchases(id)
         ON DELETE CASCADE ON UPDATE CASCADE';
    END IF;
END $$;

CREATE INDEX IF NOT EXISTS idx_purchases_supplier_id ON purchases (supplier_id);
CREATE INDEX IF NOT EXISTS idx_purchases_created_by ON purchases (created_by);
CREATE INDEX IF NOT EXISTS idx_purchases_po_date ON purchases (po_date);
CREATE INDEX IF NOT EXISTS idx_purchases_deleted_at ON purchases (deleted_at);
