-- 008_create_customer_statistics_table.sql
-- READ MODEL precalculado, mantenido por los triggers de 012.
--
-- Clave compuesta como en `clients`: el cliente se identifica por
-- (id_distributor, id), nunca por id a secas.

CREATE TABLE IF NOT EXISTS customer_statistics (
    id_distributor   INTEGER NOT NULL,
    client_id        INTEGER NOT NULL,

    pending_orders   INTEGER NOT NULL DEFAULT 0,
    completed_orders INTEGER NOT NULL DEFAULT 0,
    cancelled_orders INTEGER NOT NULL DEFAULT 0,
    total_orders     INTEGER NOT NULL DEFAULT 0,
    total_revenue    REAL    NOT NULL DEFAULT 0,
    last_order_at    TEXT,
    last_visit_at    TEXT,
    updated_at       TEXT NOT NULL,

    PRIMARY KEY (id_distributor, client_id)
);
