import type pg from 'pg';
import type { BackofficeSession } from '../domain/backoffice-session.js';
import type { BackofficeSessionRepository } from '../domain/ports.js';

interface SessionRow {
  id: string;
  user_id: string;
  created_at: Date;
  expires_at: Date;
  revoked_at: Date | null;
}

export class PgBackofficeSessionRepository implements BackofficeSessionRepository {
  constructor(private readonly pool: pg.Pool) {}

  async create(userId: string, tokenHash: string, expiresAt: Date): Promise<BackofficeSession> {
    const result = await this.pool.query<SessionRow>(
      `INSERT INTO backoffice_sessions (user_id, token_hash, expires_at)
       VALUES ($1, $2, $3) RETURNING *`,
      [userId, tokenHash, expiresAt],
    );
    const row = result.rows[0];
    if (!row) throw new Error('backoffice_sessions INSERT returned no row');
    return {
      id: row.id,
      userId: row.user_id,
      createdAt: row.created_at,
      expiresAt: row.expires_at,
      revokedAt: row.revoked_at,
    };
  }

  async revokeByTokenHash(tokenHash: string): Promise<boolean> {
    const result = await this.pool.query(
      `UPDATE backoffice_sessions SET revoked_at = now()
       WHERE token_hash = $1 AND revoked_at IS NULL`,
      [tokenHash],
    );
    return (result.rowCount ?? 0) > 0;
  }
}
