const { Store } = require('express-session');
const db = require('./db');

// Cria tabela de sessões se não existir
db.exec(`
  CREATE TABLE IF NOT EXISTS sessions (
    sid        TEXT PRIMARY KEY,
    data       TEXT NOT NULL,
    expires_at INTEGER NOT NULL
  )
`);

class SQLiteStore extends Store {
  get(sid, cb) {
    try {
      const row = db.prepare('SELECT data, expires_at FROM sessions WHERE sid=?').get(sid);
      if (!row) return cb(null, null);
      if (Date.now() > row.expires_at) {
        db.prepare('DELETE FROM sessions WHERE sid=?').run(sid);
        return cb(null, null);
      }
      cb(null, JSON.parse(row.data));
    } catch (e) { cb(e); }
  }

  set(sid, session, cb) {
    try {
      const expires = session.cookie?.expires
        ? new Date(session.cookie.expires).getTime()
        : Date.now() + 7 * 24 * 60 * 60 * 1000;
      db.prepare(`
        INSERT INTO sessions (sid, data, expires_at) VALUES (?,?,?)
        ON CONFLICT(sid) DO UPDATE SET data=excluded.data, expires_at=excluded.expires_at
      `).run(sid, JSON.stringify(session), expires);
      cb(null);
    } catch (e) { cb(e); }
  }

  destroy(sid, cb) {
    try {
      db.prepare('DELETE FROM sessions WHERE sid=?').run(sid);
      cb(null);
    } catch (e) { cb(e); }
  }

  touch(sid, session, cb) {
    this.set(sid, session, cb);
  }
}

module.exports = SQLiteStore;
