/**
 * models/trustedDevice.js
 *
 * CRUD over the trusted_devices table. The model is intentionally
 * thin — most of the policy (token generation, hashing, cookie
 * format, expiry) lives in services/trustedDevice.js. This file
 * is the SQL boundary.
 *
 * Schema (created in config/db.js):
 *   id, user_id, token_hash (sha256 hex), user_agent, ip_first_seen,
 *   last_used_at, created_at, expires_at
 */

'use strict';

const crypto = require('crypto');
const { db } = require('../config/db');

const insertStmt = db.prepare(`
  INSERT INTO trusted_devices
    (user_id, token_hash, user_agent, ip_first_seen, last_used_at, created_at, expires_at)
  VALUES (?, ?, ?, ?, ?, ?, ?)
`);

const updateLastUsed = db.prepare(`
  UPDATE trusted_devices SET last_used_at = ? WHERE id = ?
`);

const getByHashStmt = db.prepare(`
  SELECT * FROM trusted_devices WHERE token_hash = ?
`);

const getByIdStmt = db.prepare(`
  SELECT * FROM trusted_devices WHERE id = ?
`);

const listForUserStmt = db.prepare(`
  SELECT * FROM trusted_devices
   WHERE user_id = ? AND expires_at > ?
   ORDER BY last_used_at DESC, created_at DESC
`);

const deleteStmt = db.prepare(`DELETE FROM trusted_devices WHERE id = ? AND user_id = ?`);
const deleteAllStmt = db.prepare(`DELETE FROM trusted_devices WHERE user_id = ?`);

function hashToken(token) {
  return crypto.createHash('sha256').update(token).digest('hex');
}

function create({ user_id, token, user_agent = null, ip_first_seen = null, expires_at }) {
  const token_hash = hashToken(token);
  const info = insertStmt.run(user_id, token_hash, user_agent, ip_first_seen, Date.now(), Date.now(), expires_at);
  return getByIdStmt.get(info.lastInsertRowid);
}

function getByToken(token) {
  return getByHashStmt.get(hashToken(token)) || null;
}

function getById(id) {
  return getByIdStmt.get(id) || null;
}

function touch(id) {
  updateLastUsed.run(Date.now(), id);
}

function listForUser(userId) {
  return listForUserStmt.all(userId, Date.now());
}

function remove(id, userId) {
  return deleteStmt.run(id, userId);
}

function removeAllForUser(userId) {
  return deleteAllStmt.run(userId);
}

module.exports = { create, getByToken, getById, touch, listForUser, remove, removeAllForUser, hashToken };