-- John Pye Invoice Tracking
-- Migration: 001_johnpye.sql

CREATE TABLE johnpye_invoices (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id TEXT NOT NULL,
    invoice_number TEXT NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    auction_name TEXT NOT NULL,
    auction_location TEXT,
    viewing_datetime TEXT,
    delivery_type TEXT NOT NULL DEFAULT 'collection',
    delivery_method TEXT,
    items_subtotal_pence INTEGER NOT NULL DEFAULT 0,
    delivery_cost_pence INTEGER NOT NULL DEFAULT 0,
    buyers_premium_pence INTEGER NOT NULL DEFAULT 0,
    total_vat_pence INTEGER NOT NULL DEFAULT 0,
    grand_total_pence INTEGER NOT NULL DEFAULT 0,
    invoice_status TEXT NOT NULL DEFAULT 'new',
    delivery_status TEXT,
    payment_deadline TIMESTAMPTZ,
    notes TEXT,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT unique_user_invoice UNIQUE (user_id, invoice_number)
);

CREATE INDEX idx_invoices_user_id ON johnpye_invoices(user_id);
CREATE INDEX idx_invoices_status ON johnpye_invoices(user_id, invoice_status);
CREATE INDEX idx_invoices_created ON johnpye_invoices(user_id, created_at DESC);

CREATE TABLE johnpye_lot_items (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    invoice_id UUID NOT NULL REFERENCES johnpye_invoices(id) ON DELETE CASCADE,
    lot_number INTEGER NOT NULL,
    description TEXT NOT NULL,
    listing_id TEXT,
    hammer_price_pence INTEGER NOT NULL DEFAULT 0,
    vat_pence INTEGER NOT NULL DEFAULT 0,
    subtotal_pence INTEGER NOT NULL DEFAULT 0,
    CONSTRAINT unique_invoice_lot UNIQUE (invoice_id, lot_number)
);

CREATE INDEX idx_lot_items_invoice ON johnpye_lot_items(invoice_id);

-- Auto-update updated_at trigger
CREATE OR REPLACE FUNCTION update_updated_at()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trigger_invoices_updated_at
    BEFORE UPDATE ON johnpye_invoices
    FOR EACH ROW EXECUTE FUNCTION update_updated_at();
