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

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 UNIQUE INDEX IF NOT EXISTS idx_purchases_pr_number_unique
    ON purchases (pr_number)
    WHERE deleted_at IS NULL;

CREATE UNIQUE INDEX IF NOT EXISTS idx_purchases_po_number_unique
    ON purchases (po_number)
    WHERE deleted_at IS NULL AND po_number IS NOT NULL;

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);
