-- +migrate Up
CREATE TABLE entries (
  id            TEXT PRIMARY KEY,
  start_time    INTEGER NOT NULL,
  end_time      INTEGER,
  auto_stopped  INTEGER NOT NULL DEFAULT 0,
  note          TEXT,
  day_key       TEXT NOT NULL,
  updated_at    INTEGER NOT NULL,
  deleted_at    INTEGER
);
CREATE INDEX idx_entries_day ON entries(day_key);

CREATE TABLE closed_days (
  day_key       TEXT PRIMARY KEY,
  start_time    INTEGER,
  end_time      INTEGER,
  worked_ms     INTEGER NOT NULL,
  kind          TEXT NOT NULL,
  closed_at     INTEGER NOT NULL,
  updated_at    INTEGER NOT NULL
);

CREATE TABLE closed_weeks (
  week_key      TEXT PRIMARY KEY,
  expected_ms   INTEGER NOT NULL,
  worked_ms     INTEGER NOT NULL,
  delta_ms      INTEGER NOT NULL,
  closed_at     INTEGER NOT NULL,
  updated_at    INTEGER NOT NULL
);

CREATE TABLE settings_history (
  id              INTEGER PRIMARY KEY AUTOINCREMENT,
  effective_from  TEXT NOT NULL,
  hours_per_week  REAL NOT NULL,
  workdays_mask   INTEGER NOT NULL DEFAULT 31,
  timezone        TEXT NOT NULL DEFAULT 'UTC',
  created_at      INTEGER NOT NULL
);

CREATE TABLE sync_log (
  entity        TEXT NOT NULL,
  entity_id     TEXT NOT NULL,
  op            TEXT NOT NULL,
  version       INTEGER NOT NULL,
  payload       TEXT NOT NULL,
  PRIMARY KEY (entity, entity_id, version)
);

-- seed default settings
INSERT INTO settings_history (effective_from, hours_per_week, workdays_mask, timezone, created_at)
VALUES ('2000-01-01', 40.0, 31, 'UTC', unixepoch() * 1000);

-- +migrate Down
DROP TABLE IF EXISTS sync_log;
DROP TABLE IF EXISTS settings_history;
DROP TABLE IF EXISTS closed_weeks;
DROP TABLE IF EXISTS closed_days;
DROP INDEX IF EXISTS idx_entries_day;
DROP TABLE IF EXISTS entries;
