-- ERP modulaire / SaaS / exercices (SQLite) — additive
CREATE TABLE IF NOT EXISTS company_modules (
  id TEXT PRIMARY KEY,
  company_id TEXT NOT NULL,
  module_key TEXT NOT NULL,
  enabled INTEGER DEFAULT 1,
  updated_at TEXT,
  UNIQUE (company_id, module_key)
);

CREATE TABLE IF NOT EXISTS saas_plans (
  id TEXT PRIMARY KEY,
  code TEXT NOT NULL UNIQUE,
  name TEXT NOT NULL,
  max_users INTEGER DEFAULT 5,
  max_companies INTEGER DEFAULT 1,
  max_storage_mb INTEGER DEFAULT 1024,
  modules_json TEXT,
  price_monthly REAL DEFAULT 0,
  active INTEGER DEFAULT 1,
  created_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS company_subscriptions (
  id TEXT PRIMARY KEY,
  company_id TEXT NOT NULL,
  plan_id TEXT NOT NULL,
  status TEXT DEFAULT 'ACTIVE',
  starts_at TEXT,
  ends_at TEXT,
  created_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS user_branches (
  user_id TEXT NOT NULL,
  branch_id TEXT NOT NULL,
  company_id TEXT NOT NULL,
  PRIMARY KEY (user_id, branch_id)
);

CREATE TABLE IF NOT EXISTS fiscal_years (
  id TEXT PRIMARY KEY,
  company_id TEXT NOT NULL,
  label TEXT NOT NULL,
  year INTEGER NOT NULL,
  starts_on TEXT NOT NULL,
  ends_on TEXT NOT NULL,
  is_current INTEGER DEFAULT 0,
  closed INTEGER DEFAULT 0,
  UNIQUE (company_id, year)
);

CREATE TABLE IF NOT EXISTS numbering_rules (
  id TEXT PRIMARY KEY,
  company_id TEXT NOT NULL,
  doc_type TEXT NOT NULL,
  prefix TEXT NOT NULL,
  pad INTEGER DEFAULT 5,
  include_year INTEGER DEFAULT 1,
  UNIQUE (company_id, doc_type)
);

CREATE TABLE IF NOT EXISTS contracts (
  id TEXT PRIMARY KEY,
  company_id TEXT NOT NULL,
  number TEXT NOT NULL,
  contract_type TEXT DEFAULT 'AUTRE',
  title TEXT,
  party_type TEXT DEFAULT 'CLIENT',
  customer_id TEXT,
  supplier_id TEXT,
  driver_id TEXT,
  vehicle_id TEXT,
  start_date TEXT,
  end_date TEXT,
  amount REAL DEFAULT 0,
  frequency TEXT,
  auto_renew INTEGER DEFAULT 0,
  status TEXT DEFAULT 'ACTIF',
  document_path TEXT,
  notes TEXT,
  created_by TEXT,
  created_at TEXT NOT NULL,
  UNIQUE (company_id, number)
);

CREATE TABLE IF NOT EXISTS ai_queries (
  id TEXT PRIMARY KEY,
  company_id TEXT NOT NULL,
  user_id TEXT NOT NULL,
  question TEXT NOT NULL,
  answer TEXT,
  created_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS gps_integrations (
  id TEXT PRIMARY KEY,
  company_id TEXT NOT NULL UNIQUE,
  provider TEXT DEFAULT 'NONE',
  api_base_url TEXT,
  api_key TEXT,
  enabled INTEGER DEFAULT 0,
  notes TEXT,
  updated_at TEXT
);

CREATE INDEX IF NOT EXISTS idx_company_modules_co ON company_modules(company_id);
CREATE INDEX IF NOT EXISTS idx_contracts_co ON contracts(company_id);
CREATE INDEX IF NOT EXISTS idx_fiscal_years_co ON fiscal_years(company_id);
