import pool from '../db';
import { TzSource } from './user';

export interface TouristPass {
  id: string;
  user_id: string;
  purchased_at_utc: string;
  purchase_timezone_iana: string;
  timezone_source: string;
  expires_at_utc: string;
  credits_granted: number;
  status: 'ACTIVE' | 'EXPIRED' | 'REPLACED';
  purchase_ip: string | null;
  purchase_geo: any;
  user_agent: string | null;
  payment_txn_id: string | null;
  stripe_session_id: string | null;
  replaced_by: string | null;
  created_at: string;
}

/**
 * Create an auditable tourist pass record.
 * Also marks any previous ACTIVE passes for this user as REPLACED.
 */
export async function createTouristPass(params: {
  userId: string;
  timezone: string;
  tzSource: TzSource;
  expiresAtUtc: string;
  creditsGranted: number;
  purchaseIp?: string | null;
  purchaseGeo?: any;
  userAgent?: string | null;
  stripeSessionId?: string | null;
}): Promise<TouristPass> {
  // Create the new pass
  const { rows } = await pool.query(
    `INSERT INTO rm_tourist_passes
     (user_id, purchase_timezone_iana, timezone_source, expires_at_utc, credits_granted,
      purchase_ip, purchase_geo, user_agent, stripe_session_id)
     VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
     RETURNING *`,
    [
      params.userId,
      params.timezone,
      params.tzSource,
      params.expiresAtUtc,
      params.creditsGranted,
      params.purchaseIp || null,
      params.purchaseGeo ? JSON.stringify(params.purchaseGeo) : null,
      params.userAgent || null,
      params.stripeSessionId || null,
    ]
  );

  const newPass = rows[0];

  // Mark previous ACTIVE passes as REPLACED
  await pool.query(
    `UPDATE rm_tourist_passes
     SET status = 'REPLACED', replaced_by = $1
     WHERE user_id = $2 AND id != $1 AND status = 'ACTIVE'`,
    [newPass.id, params.userId]
  );

  return newPass;
}

export async function getActivePass(userId: string): Promise<TouristPass | null> {
  const { rows } = await pool.query(
    `SELECT * FROM rm_tourist_passes
     WHERE user_id = $1 AND status = 'ACTIVE' AND expires_at_utc > NOW()
     ORDER BY created_at DESC LIMIT 1`,
    [userId]
  );
  return rows[0] || null;
}

export async function getExpiredActivePasses(): Promise<TouristPass[]> {
  const { rows } = await pool.query(
    `SELECT * FROM rm_tourist_passes
     WHERE status = 'ACTIVE' AND expires_at_utc <= NOW()`
  );
  return rows;
}

export async function markPassExpired(passId: string): Promise<void> {
  await pool.query(
    `UPDATE rm_tourist_passes SET status = 'EXPIRED' WHERE id = $1`,
    [passId]
  );
}
