import { query } from '../db/client.js'

export type AdminSessionRow = {
  id: number
  session_id: string
  user_id: number
  status: string
  issued_at: string
  last_seen_at: string
  expires_at: string
  revoked_at: string | null
  created_at: string
  updated_at: string
}

export async function createAdminSession(input: {
  sessionId: string
  userId: number
  issuedAt: string
  expiresAt: string
  now: string
}): Promise<AdminSessionRow | null> {
  const result = await query<AdminSessionRow>(
    `
      INSERT INTO admin_sessions (
        session_id, user_id, status, issued_at, last_seen_at,
        expires_at, revoked_at, created_at, updated_at
      ) VALUES ($1, $2, 'active', $3, $3, $4, NULL, $5, $5)
      RETURNING *
    `,
    [input.sessionId, input.userId, input.issuedAt, input.expiresAt, input.now],
  )
  return result.rows[0] || null
}

export async function getActiveAdminSession(
  sessionId: string,
  now: string,
): Promise<AdminSessionRow | null> {
  const result = await query<AdminSessionRow>(
    `
      SELECT *
      FROM admin_sessions
      WHERE session_id = $1
        AND status = 'active'
        AND expires_at > $2
      LIMIT 1
    `,
    [sessionId, now],
  )
  return result.rows[0] || null
}

export async function touchAdminSession(sessionId: string, now: string): Promise<boolean> {
  const result = await query(
    `
      UPDATE admin_sessions
      SET last_seen_at = $2, updated_at = $2
      WHERE session_id = $1 AND status = 'active' AND expires_at > $2
    `,
    [sessionId, now],
  )
  return result.rowCount === 1
}

export async function revokeAdminSession(sessionId: string, now: string): Promise<boolean> {
  const result = await query(
    `
      UPDATE admin_sessions
      SET status = 'revoked', revoked_at = $2, updated_at = $2
      WHERE session_id = $1 AND status = 'active'
    `,
    [sessionId, now],
  )
  return result.rowCount === 1
}
