/**
 * Analytics SQLite Database — Local aggregated metrics
 * Stores daily/monthly aggregates for fast historical queries
 */
const Database = require('better-sqlite3');
const path = require('path');

const DB_PATH = path.join(__dirname, '..', 'data', 'analytics.db');
const db = new Database(DB_PATH);

db.pragma('journal_mode = WAL');

// Daily metrics table
db.exec(`
  CREATE TABLE IF NOT EXISTS daily_metrics (
    date TEXT NOT NULL,
    product TEXT NOT NULL,
    transactions INTEGER DEFAULT 0,
    volume_usd REAL DEFAULT 0,
    volume_brl REAL DEFAULT 0,
    revenue REAL DEFAULT 0,
    avg_spread REAL DEFAULT 0,
    avg_ticket REAL DEFAULT 0,
    unique_clients INTEGER DEFAULT 0,
    PRIMARY KEY (date, product)
  )
`);

// Client health daily snapshot
db.exec(`
  CREATE TABLE IF NOT EXISTS client_health_daily (
    date TEXT NOT NULL,
    id_conta INTEGER NOT NULL,
    health_score INTEGER DEFAULT 0,
    churn_risk TEXT DEFAULT 'medium',
    volume_usd REAL DEFAULT 0,
    tx_count INTEGER DEFAULT 0,
    last_tx_date TEXT,
    PRIMARY KEY (date, id_conta)
  )
`);

// Monthly revenue per client
db.exec(`
  CREATE TABLE IF NOT EXISTS monthly_revenue (
    month TEXT NOT NULL,
    id_conta INTEGER NOT NULL,
    revenue REAL DEFAULT 0,
    volume_usd REAL DEFAULT 0,
    tx_count INTEGER DEFAULT 0,
    PRIMARY KEY (month, id_conta)
  )
`);

// Indexes for fast lookups
db.exec(`CREATE INDEX IF NOT EXISTS idx_daily_date ON daily_metrics(date)`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_health_date ON client_health_daily(date)`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_monthly_month ON monthly_revenue(month)`);

module.exports = db;
