/**
 * Esquema de la BD local (SQLite). Refleja las entidades del bundle (PULL) y
 * añade dos colas de salida (outbox de operaciones y de media) más una tabla
 * `meta` para el cursor de sync por proyecto.
 *
 * Versionado simple por `user_version` de SQLite (ver database.ts).
 */

export const SCHEMA_VERSION = 2;

export const SCHEMA_SQL = `
PRAGMA journal_mode = WAL;
PRAGMA foreign_keys = ON;

-- Clave/valor: cursor de sync (key 'cursor:<projectId>'), proyecto activo, etc.
CREATE TABLE IF NOT EXISTS meta (
  key   TEXT PRIMARY KEY,
  value TEXT
);

-- ===== Entidades del bundle (espejo del servidor) =====
-- 'id' es el id del servidor. 'updated_at' alimenta el delta/last-write-wins.

CREATE TABLE IF NOT EXISTS projects (
  id          INTEGER PRIMARY KEY,
  reference   TEXT,
  name        TEXT,
  address     TEXT,
  lat         REAL,
  lng         REAL,
  status      TEXT,
  updated_at  TEXT
);

CREATE TABLE IF NOT EXISTS phases (
  id               INTEGER PRIMARY KEY,
  project_id       INTEGER,
  name             TEXT,
  "order"          INTEGER,
  color            TEXT,
  progress_percent REAL,
  updated_at       TEXT
);

CREATE TABLE IF NOT EXISTS layers (
  id          INTEGER PRIMARY KEY,
  project_id  INTEGER,
  phase_id    INTEGER,
  name        TEXT,
  color       TEXT,
  updated_at  TEXT
);

CREATE TABLE IF NOT EXISTS features (
  id           INTEGER PRIMARY KEY,
  project_id   INTEGER,
  layer_id     INTEGER,
  name         TEXT,
  geometry     TEXT,          -- GeoJSON serializado
  status       TEXT,
  progress     REAL,
  responsible  TEXT,
  template_id  INTEGER,
  updated_at   TEXT,
  -- columnas locales para conciliar creaciones offline:
  local_uuid   TEXT,          -- uuid de la operación que la creó (si nació offline)
  dirty        INTEGER DEFAULT 0  -- 1 = hay cambios locales sin confirmar
);

CREATE TABLE IF NOT EXISTS inspections (
  id           INTEGER PRIMARY KEY,
  project_id   INTEGER,
  feature_id   INTEGER,
  layer_id     INTEGER,
  template_id  INTEGER,
  user_id      INTEGER,
  data         TEXT,          -- objeto serializado
  status       TEXT,
  result       TEXT,
  notes        TEXT,
  created_at   TEXT,
  updated_at   TEXT,
  local_uuid   TEXT,
  dirty        INTEGER DEFAULT 0
);

CREATE TABLE IF NOT EXISTS issues (
  id               INTEGER PRIMARY KEY,
  project_id       INTEGER,
  feature_id       INTEGER,
  title            TEXT,
  description      TEXT,
  status           TEXT,
  priority         TEXT,
  type             TEXT,
  reported_by      INTEGER,
  assigned_to      INTEGER,
  resolution_notes TEXT,
  resolved_at      TEXT,
  updated_at       TEXT,
  local_uuid       TEXT,
  dirty            INTEGER DEFAULT 0
);

CREATE TABLE IF NOT EXISTS issue_tasks (
  id           INTEGER PRIMARY KEY,
  issue_id     INTEGER,
  title        TEXT,
  is_done      INTEGER,
  done_at      TEXT,
  done_by      INTEGER,
  assigned_to  INTEGER,
  due_date     TEXT,
  "order"      INTEGER,
  updated_at   TEXT,
  local_uuid   TEXT,
  dirty        INTEGER DEFAULT 0
);

CREATE TABLE IF NOT EXISTS issue_comments (
  id           INTEGER PRIMARY KEY,
  issue_id     INTEGER,
  user_id      INTEGER,
  body         TEXT,
  created_at   TEXT,
  updated_at   TEXT,
  local_uuid   TEXT
);

CREATE TABLE IF NOT EXISTS templates (
  id           INTEGER PRIMARY KEY,
  project_id   INTEGER,
  phase_id     INTEGER,
  name         TEXT,
  description  TEXT,
  fields       TEXT,          -- array serializado
  version      TEXT,
  hash         TEXT,
  updated_at   TEXT
);

CREATE TABLE IF NOT EXISTS media (
  id            INTEGER PRIMARY KEY,
  uuid          TEXT,
  parent_entity TEXT,
  parent_id     INTEGER,
  url           TEXT,
  name          TEXT,
  file_type     TEXT,
  category      TEXT,
  updated_at    TEXT
);

-- ===== Colas de salida (outbox) =====

-- Operaciones de /sync. 'uuid' = clave de idempotencia (PK).
CREATE TABLE IF NOT EXISTS outbox (
  uuid               TEXT PRIMARY KEY,
  entity             TEXT NOT NULL,
  op                 TEXT NOT NULL,        -- create | update
  data               TEXT NOT NULL,        -- JSON del payload 'data'
  client_updated_at  TEXT NOT NULL,
  status             TEXT NOT NULL DEFAULT 'pending', -- pending|sent|conflict|error
  server_id          INTEGER,
  error              TEXT,
  server_payload     TEXT,                 -- JSON del valor del servidor en conflicto
  attempts           INTEGER NOT NULL DEFAULT 0,
  created_at         TEXT NOT NULL
);

-- Ficheros pendientes de subir a /media.
CREATE TABLE IF NOT EXISTS media_outbox (
  uuid           TEXT PRIMARY KEY,
  parent_entity  TEXT NOT NULL,
  parent_id      INTEGER NOT NULL,
  local_uri      TEXT NOT NULL,
  file_name      TEXT,
  mime_type      TEXT,
  category       TEXT,
  description    TEXT,
  status         TEXT NOT NULL DEFAULT 'pending', -- pending|sent|error
  media_id       INTEGER,
  error          TEXT,
  attempts       INTEGER NOT NULL DEFAULT 0,
  created_at     TEXT NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_outbox_status ON outbox(status);
CREATE INDEX IF NOT EXISTS idx_media_outbox_status ON media_outbox(status);
CREATE INDEX IF NOT EXISTS idx_phases_project ON phases(project_id);
CREATE INDEX IF NOT EXISTS idx_layers_phase ON layers(phase_id);
CREATE INDEX IF NOT EXISTS idx_features_layer ON features(layer_id);
CREATE INDEX IF NOT EXISTS idx_issues_project ON issues(project_id);
CREATE INDEX IF NOT EXISTS idx_issue_tasks_issue ON issue_tasks(issue_id);
CREATE INDEX IF NOT EXISTS idx_issue_comments_issue ON issue_comments(issue_id);
`;
