-- /home/Autopartes/pos/migrations/v1.1_pos_tables.sql
-- POS Plan 3: Additional tables for sale payments and layaway items.
-- Run against each tenant DB.

-- Sale payments: tracks individual payment methods for a sale (especially mixed payments)
CREATE TABLE IF NOT EXISTS sale_payments (
    id              SERIAL PRIMARY KEY,
    sale_id         INTEGER REFERENCES sales(id),
    register_id     INTEGER REFERENCES cash_registers(id),
    method          VARCHAR(20) NOT NULL,           -- efectivo, transferencia, tarjeta
    amount          NUMERIC(12,2) NOT NULL,
    reference       VARCHAR(100),                    -- transaction ref for non-cash
    created_at      TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_sale_payments_sale ON sale_payments(sale_id);

-- Customer payments: tracks credit payments (abonos) against customer balance
CREATE TABLE IF NOT EXISTS customer_payments (
    id              SERIAL PRIMARY KEY,
    customer_id     INTEGER REFERENCES customers(id),
    amount          NUMERIC(12,2) NOT NULL,
    payment_method  VARCHAR(20) NOT NULL DEFAULT 'efectivo',
    reference       VARCHAR(100),
    employee_id     INTEGER REFERENCES employees(id),
    register_id     INTEGER REFERENCES cash_registers(id),
    created_at      TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_customer_payments_customer ON customer_payments(customer_id);

-- Layaway items: line items for a layaway (mirrors quotation_items structure)
CREATE TABLE IF NOT EXISTS layaway_items (
    id              SERIAL PRIMARY KEY,
    layaway_id      INTEGER REFERENCES layaways(id),
    inventory_id    INTEGER REFERENCES inventory(id),
    part_number     VARCHAR(100),
    name            VARCHAR(300),
    quantity        INTEGER NOT NULL,
    unit_price      NUMERIC(12,2) NOT NULL,
    discount_pct    NUMERIC(5,2) DEFAULT 0,
    tax_rate        NUMERIC(5,4) DEFAULT 0.16,
    subtotal        NUMERIC(12,2) NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_layaway_items_layaway ON layaway_items(layaway_id);

-- Additional indexes for POS query performance
CREATE INDEX IF NOT EXISTS idx_sales_register ON sales(register_id) WHERE status = 'completed';
CREATE INDEX IF NOT EXISTS idx_sales_customer ON sales(customer_id);
CREATE INDEX IF NOT EXISTS idx_sales_created ON sales(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_sales_branch_date ON sales(branch_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_quotations_customer ON quotations(customer_id);
CREATE INDEX IF NOT EXISTS idx_layaways_customer ON layaways(customer_id);
CREATE INDEX IF NOT EXISTS idx_cash_registers_employee ON cash_registers(employee_id) WHERE status = 'open';
