-- 006: tables pour le dashboard admin (auth, audit, logs crawler)

CREATE TABLE IF NOT EXISTS admin_users (
  id            BIGSERIAL PRIMARY KEY,
  username      TEXT UNIQUE NOT NULL,
  password_hash TEXT NOT NULL,
  created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
  last_login_at TIMESTAMPTZ
);

CREATE TABLE IF NOT EXISTS admin_login_attempts (
  id         BIGSERIAL PRIMARY KEY,
  username   TEXT NOT NULL,
  ip         TEXT,
  success    BOOLEAN NOT NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_admin_login_attempts_username_time
  ON admin_login_attempts (username, created_at DESC);

CREATE TABLE IF NOT EXISTS admin_audit_log (
  id             BIGSERIAL PRIMARY KEY,
  admin_username TEXT NOT NULL,
  action         TEXT NOT NULL,
  target_table   TEXT NOT NULL,
  target_id      TEXT,
  before_data    JSONB,
  after_data     JSONB,
  created_at     TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_admin_audit_log_created_at ON admin_audit_log (created_at DESC);

CREATE TABLE IF NOT EXISTS crawl_log (
  id         BIGSERIAL PRIMARY KEY,
  run_id     BIGINT REFERENCES crawl_run(id) ON DELETE SET NULL,
  level      TEXT NOT NULL DEFAULT 'info',
  message    TEXT NOT NULL,
  ma_id      BIGINT,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_crawl_log_created_at ON crawl_log (created_at DESC);
CREATE INDEX IF NOT EXISTS idx_crawl_log_run_id ON crawl_log (run_id);
