import { BadRequestException, ForbiddenException } from '@nestjs/common';
import { CLS_USER_PERMISSIONS } from '../cls/cls.constants';
import { AccessLevel, ModuleName } from '../../entities/role-permission.entity';

/** Anything with a raw `query` — a TypeORM EntityManager or Repository.manager. */
interface Querier {
  query(sql: string, params?: unknown[]): Promise<unknown>;
}

/**
 * H19 — a booking that is On hold or Cancelled takes no edits (assign,
 * cost, pax, itinerary, change requests). Only a status change resumes
 * it. Raw SQL with an explicit tenant filter (tenancy.md caution).
 * Missing bookings pass — callers raise their own 404.
 */
export async function assertBookingOpen(
  db: Querier,
  tenantId: string,
  bookingId: string,
): Promise<void> {
  const rows = (await db.query(
    `SELECT booking_number, status FROM bookings
      WHERE id = $1 AND tenant_id = $2 AND is_deleted = false`,
    [bookingId, tenantId],
  )) as Array<{ booking_number: string | null; status: string }>;
  const b = rows[0];
  if (!b) return;
  const label = b.booking_number ? `Booking ${b.booking_number}` : 'This booking';
  if (b.status === 'on_hold') {
    throw new BadRequestException(`${label} is on hold — resume it before making changes.`);
  }
  if (b.status === 'cancelled') {
    throw new BadRequestException(`${label} is cancelled — it can't be changed.`);
  }
}

/** True when the signed-in user's role has Past Booking Edit set to All (`delete`). */
export function canEditPastBookings(cls: { get<T>(key: string): T }): boolean {
  const permissions = cls.get<Record<string, string> | null>(CLS_USER_PERMISSIONS) ?? {};
  return permissions[ModuleName.PAST_BOOKING_EDIT] === AccessLevel.DELETE;
}

/**
 * Past-booking lock (client 2026-11-02): a completed booking, or one whose
 * travel end date is before today (Asia/Kolkata, the office's day), can be
 * edited only by roles with Past Booking Edit in Settings → Roles →
 * Permissions. Movement Dashboard operations (driver, status, supplier)
 * don't call this: ops still close out yesterday's trips.
 */
export async function assertPastBookingEditAllowed(
  db: Querier,
  tenantId: string,
  bookingId: string,
  allowed: boolean,
): Promise<void> {
  if (allowed) return;
  const rows = (await db.query(
    `SELECT b.booking_number, b.status, q.end_date::text AS end_date
       FROM bookings b
       LEFT JOIN queries q ON q.id = b.query_id AND q.tenant_id = b.tenant_id
      WHERE b.id = $1 AND b.tenant_id = $2 AND b.is_deleted = false`,
    [bookingId, tenantId],
  )) as Array<{ booking_number: string | null; status: string; end_date: string | null }>;
  const b = rows[0];
  if (!b) return;
  const today = new Date().toLocaleDateString('en-CA', { timeZone: 'Asia/Kolkata' });
  if (b.status === 'completed' || (!!b.end_date && b.end_date < today)) {
    const label = b.booking_number ? `Booking ${b.booking_number}` : 'This booking';
    throw new ForbiddenException(
      `${label} is a past booking — your role can't edit it. Ask an admin to give your role Past Booking Edit permission.`,
    );
  }
}

/**
 * H18 — while accounts hold the booking's settlement, changes that move
 * money (supplier, cost, pax, itinerary, approvals) are refused up
 * front. Before, the edit saved and the payable / delta was silently
 * dropped. Dispatch-only edits (driver, vehicle, times) don't call this.
 */
export async function assertSettlementNotHeld(
  db: Querier,
  tenantId: string,
  bookingId: string,
): Promise<void> {
  const rows = (await db.query(
    `SELECT hold_reason FROM booking_settlement_masters
      WHERE booking_id = $1 AND tenant_id = $2 AND is_deleted = false
        AND overall_status = 'HOLD'
      LIMIT 1`,
    [bookingId, tenantId],
  )) as Array<{ hold_reason: string | null }>;
  if (rows.length === 0) return;
  const reason = rows[0].hold_reason ? ` (${rows[0].hold_reason})` : '';
  throw new BadRequestException(
    `Payments for this booking are on hold${reason} — ask accounts to release the hold before changing supplier, cost or pax.`,
  );
}

/** Row fields whose change raises or moves a payable / collection. */
const MONEY_FIELDS = [
  'supplier_id',
  'supplier_name_text',
  'suppliers',
  'actual_supplier_cost',
  'adults_override',
  'children_override',
  'quantity',
  'unit_price',
  'subtotal',
  'vehicle_type_id',
  'ticket_id',
  'addon_charge',
] as const;

/** True when a row patch sets any money field (see MONEY_FIELDS). */
export function touchesMoney(dto: object): boolean {
  return MONEY_FIELDS.some((k) => (dto as Record<string, unknown>)[k] !== undefined);
}
