import { createHmac, randomInt, randomUUID, timingSafeEqual } from 'node:crypto';
import { Prisma, RateBasis, Role, TenantKind } from '@prisma/client';
import { env, publicWebUrl } from '../../config/env';
import { prismaUnscoped } from '../../lib/prisma';
import { hashPassword } from '../../lib/password';
import { emailFailed, isEmailConfigured, sendEmail } from '../../lib/email';
import { otpEmail, trialWelcomeEmail } from '../../lib/email-templates';
import { BadRequestError, ConflictError, NotFoundError, ServiceUnavailableError, TooManyRequestsError } from '../../lib/errors';
import { maskEmail } from '../auth/two-factor.service';
import { signInNewAccount } from '../auth/auth.service';
import { createTenantWithAdmin } from '../tenants/tenant.service';
import { ingestLead } from '../crm/crm-leads.service';
import { phoneKeyOf } from '../crm/crm-contacts.service';
import { openTrialDeal } from '../crm/crm-deals.service';
import { floorFromRoomNumber } from '../rooms/rooms.service';

/**
 * The self-serve free trial (Sprint L2).
 *
 * An owner fills in one form on the app's /start-trial page, proves their
 * email with a 6-digit code, and lands signed in to a hostel that already has
 * its rooms and beds. Nothing exists until the code is right: the form waits
 * in a TrialSignup row (password already hashed, code HMAC'd), so a typo'd
 * email leaves no account behind.
 *
 * One trial per phone and per email: an address or number that already
 * belongs to a hostel account is refused, politely, with a pointer to sign in.
 *
 * On success the owner also becomes a CRM lead (source "Trial signup") with
 * a deal in "Trial started" linked to the new hostel, and the lead owner is
 * alerted like any other lead.
 */

export const TRIAL_DAYS = 7;
/** ₹20 per bed per month, for a year: what the deal is worth if they stay. */
const BED_PRICE_YEAR = 20 * 12;
const CODE_LENGTH = 6;
const MAX_ATTEMPTS = 5;
const MAX_SENDS = 5;
const RESEND_COOLDOWN_MS = 30_000;
const MAX_STARTS_PER_HOUR = 5;

export interface TrialForm {
  name: string;
  email: string;
  phone: string;
  password: string;
  hostelName: string;
  kind: 'HOSTEL' | 'DORMITORY';
  city: string;
  state?: string;
  rooms: number;
  bedsPerRoom: number;
  consent: boolean;
  page?: string;
  utmSource?: string;
  utmMedium?: string;
  utmCampaign?: string;
}

/** What the form keeps until the code is right (the password lives hashed beside it). */
type Pending = Omit<TrialForm, 'password' | 'email' | 'name'>;

export interface TrialChallenge {
  signupId: string;
  emailHint: string;
  expiresInSeconds: number;
  resendAfterSeconds: number;
  /** Only when AUTH_OTP_ECHO is on (never in production): the code itself. */
  devCode?: string;
}

function newCode(): string {
  return String(randomInt(0, 10 ** CODE_LENGTH)).padStart(CODE_LENGTH, '0');
}

/** Keyed with a server secret and bound to the row, so a leaked table is useless. */
function hashCode(id: string, code: string): string {
  return createHmac('sha256', `${env.JWT_REFRESH_SECRET}:trial-signup`).update(`${id}:${code}`).digest('hex');
}

function sameHash(a: string, b: string): boolean {
  const x = Buffer.from(a, 'hex');
  const y = Buffer.from(b, 'hex');
  return x.length === y.length && timingSafeEqual(x, y);
}

/** Without mail the code has nowhere to go; development logs it instead. */
function assertCanDeliver() {
  if (isEmailConfigured()) return;
  if (env.NODE_ENV === 'development' || env.NODE_ENV === 'test') return;
  throw new ServiceUnavailableError('We cannot send email right now, so the trial cannot start. Please try again later.', 'EMAIL_NOT_CONFIGURED');
}

async function sendCode(id: string, to: string, name: string, code: string) {
  const mail = otpEmail({ name, code, minutes: env.OTP_TTL_MINUTES, purpose: 'TRIAL' });
  const result = await sendEmail(to, mail.subject, mail.text, mail.html);
  if (emailFailed(result)) throw new ServiceUnavailableError('We could not send the code to that email. Check the address and try again.', 'EMAIL_SEND_FAILED');
  if (result.mode === 'log') {
    // eslint-disable-next-line no-console
    console.log(`[trial dry-run] code for ${to}: ${code} (signup ${id})`);
  }
}

function challengeOf(id: string, email: string, code: string, lastSentAt: Date, expiresAt: Date): TrialChallenge {
  return {
    signupId: id,
    emailHint: maskEmail(email),
    expiresInSeconds: Math.max(0, Math.round((expiresAt.getTime() - Date.now()) / 1000)),
    resendAfterSeconds: Math.max(0, Math.round((lastSentAt.getTime() + RESEND_COOLDOWN_MS - Date.now()) / 1000)),
    ...(env.AUTH_OTP_ECHO ? { devCode: code } : {}),
  };
}

const ALREADY = 'already has a HostelCare account. Sign in instead, or write to us if you need a hand.';

/** One trial per email and per phone: refuse anything already behind an account. */
async function assertNew(email: string, phoneKey: string) {
  const user = await prismaUnscoped.user.findUnique({ where: { email }, select: { id: true } });
  if (user) throw new ConflictError(`This email ${ALREADY}`, 'TRIAL_EMAIL_TAKEN');
  const done = await prismaUnscoped.trialSignup.findFirst({ where: { completedAt: { not: null }, OR: [{ email }, { phoneKey }] }, select: { email: true } });
  if (done) throw new ConflictError(done.email === email ? `This email ${ALREADY}` : `This phone number ${ALREADY}`, done.email === email ? 'TRIAL_EMAIL_TAKEN' : 'TRIAL_PHONE_TAKEN');
  // A hostel admin's phone is free text; compare the last ten digits.
  const phoneTaken = await prismaUnscoped.$queryRaw<{ id: string }[]>`
    SELECT "id" FROM "User"
    WHERE "role" = ${Role.HOSTEL_ADMIN}::"Role" AND "phone" IS NOT NULL
      AND right(regexp_replace("phone", '[^0-9]', '', 'g'), 10) = ${phoneKey}
    LIMIT 1`;
  if (phoneTaken.length) throw new ConflictError(`This phone number ${ALREADY}`, 'TRIAL_PHONE_TAKEN');
}

/**
 * The plan a trial runs on. Plans cap beds, and the default plan is often
 * the small free one, so a trial gets the default plan when it fits and
 * otherwise the smallest active plan that holds its beds — the owner tries
 * HostelCare at their real size. The super admin picks the paid plan at
 * renewal as for any hostel.
 */
async function trialPlan(beds: number): Promise<string | null> {
  const plans = await prismaUnscoped.plan.findMany({ where: { isActive: true }, select: { id: true, isDefault: true, maxBeds: true, monthlyPrice: true } });
  const fits = plans.filter((p) => p.maxBeds == null || p.maxBeds >= beds);
  if (!plans.length) return null;
  const pick = fits.find((p) => p.isDefault) ?? fits.sort((x, y) => (x.maxBeds ?? Infinity) - (y.maxBeds ?? Infinity) || x.monthlyPrice - y.monthlyPrice)[0];
  if (!pick) {
    const most = Math.max(...plans.map((p) => p.maxBeds ?? 0));
    throw new BadRequestError(`The free trial covers up to ${most} beds. Start with fewer rooms now and add the rest later, or write to us for a bigger trial.`, 'TRIAL_TOO_MANY_BEDS');
  }
  return pick.id;
}

/** Step 1: check the form, keep it, and email a code. */
export async function startTrial(form: TrialForm, ip: string | null, now = new Date()): Promise<TrialChallenge> {
  const email = form.email.trim().toLowerCase();
  const phoneKey = phoneKeyOf(form.phone);
  if (!phoneKey || phoneKey.length < 10) throw new BadRequestError('Enter a phone number with at least 10 digits.', 'INVALID_PHONE');
  await assertNew(email, phoneKey);
  await trialPlan(form.rooms * form.bedsPerRoom);
  assertCanDeliver();

  const hourAgo = new Date(now.getTime() - 60 * 60 * 1000);
  const recent = await prismaUnscoped.trialSignup.count({ where: { createdAt: { gte: hourAgo }, OR: [{ email }, { phoneKey }] } });
  if (recent >= MAX_STARTS_PER_HOUR) throw new TooManyRequestsError('Too many tries for this email or phone. Wait a while and try again.', 'TRIAL_RATE_LIMITED');

  // Housekeeping: unfinished signups are worthless after a day.
  await prismaUnscoped.trialSignup.deleteMany({ where: { completedAt: null, createdAt: { lt: new Date(now.getTime() - 24 * 60 * 60 * 1000) } } });

  const { password, name, email: _e, ...rest } = form;
  const data: Pending = { ...rest, phone: form.phone.trim(), hostelName: form.hostelName.trim(), city: form.city.trim() };
  const id = randomUUID();
  const code = newCode();
  const expiresAt = new Date(now.getTime() + env.OTP_TTL_MINUTES * 60 * 1000);
  // Only the newest unfinished signup for this email can be confirmed.
  await prismaUnscoped.trialSignup.updateMany({ where: { email, completedAt: null }, data: { expiresAt: now } });
  await prismaUnscoped.trialSignup.create({
    data: { id, email, phoneKey, name: name.trim(), data: data as unknown as Prisma.InputJsonValue, passwordHash: await hashPassword(password), codeHash: hashCode(id, code), expiresAt, lastSentAt: now, ip },
  });
  try {
    await sendCode(id, email, name.trim(), code);
  } catch (e) {
    await prismaUnscoped.trialSignup.delete({ where: { id } }).catch(() => {});
    throw e;
  }
  return challengeOf(id, email, code, now, expiresAt);
}

async function openSignup(id: string) {
  const s = await prismaUnscoped.trialSignup.findUnique({ where: { id } });
  if (!s || s.completedAt) throw new NotFoundError('This signup has finished or expired. Start again.', 'TRIAL_NOT_FOUND');
  return s;
}

/** A new code on the same signup. The attempt counter carries over. */
export async function resendTrialCode(id: string, now = new Date()): Promise<TrialChallenge> {
  assertCanDeliver();
  const s = await openSignup(id);
  if (s.expiresAt.getTime() + 24 * 60 * 60 * 1000 < now.getTime()) throw new NotFoundError('This signup has expired. Start again.', 'TRIAL_NOT_FOUND');
  if (s.attempts >= MAX_ATTEMPTS) throw new TooManyRequestsError('Too many wrong codes. Start again.', 'TRIAL_LOCKED');
  if (s.sends >= MAX_SENDS) throw new TooManyRequestsError('That is enough codes for one signup. Start again in a while.', 'TRIAL_RATE_LIMITED');
  const wait = s.lastSentAt.getTime() + RESEND_COOLDOWN_MS - now.getTime();
  if (wait > 0) throw new TooManyRequestsError(`Wait ${Math.ceil(wait / 1000)} seconds before asking for another code.`, 'OTP_COOLDOWN');
  const code = newCode();
  const expiresAt = new Date(now.getTime() + env.OTP_TTL_MINUTES * 60 * 1000);
  await prismaUnscoped.trialSignup.update({ where: { id }, data: { codeHash: hashCode(id, code), expiresAt, lastSentAt: now, sends: { increment: 1 } } });
  await sendCode(id, s.email, s.name, code);
  return challengeOf(id, s.email, code, now, expiresAt);
}

/** Rooms 101, 102, … with beds A, B, C … (a dormitory's 1, 2, 3 …); the owner renames them later. */
async function buildRooms(tenantId: string, propertyId: string, p: Pending) {
  const daily = p.kind === 'DORMITORY';
  for (let i = 0; i < p.rooms; i++) {
    const room = await prismaUnscoped.room.create({
      // A floor, or none of its beds could be assigned (floorFromRoomNumber).
      data: { tenantId, propertyId, number: String(101 + i), floor: floorFromRoomNumber(String(101 + i)), rateBasis: daily ? RateBasis.DAILY : RateBasis.MONTHLY },
      select: { id: true },
    });
    await prismaUnscoped.bed.createMany({
      data: Array.from({ length: p.bedsPerRoom }, (_, b) => ({ tenantId, roomId: room.id, label: daily || b >= 26 ? String(b + 1) : String.fromCharCode(65 + b) })),
    });
  }
}

const fmtDay = (iso: string) => new Date(`${iso}T12:00:00Z`).toLocaleDateString('en-IN', { day: 'numeric', month: 'long', year: 'numeric', timeZone: 'Asia/Kolkata' });

/** Step 2: the right code creates the hostel and signs the owner in. */
export async function verifyTrial(id: string, code: string, now = new Date()) {
  const s = await openSignup(id);
  if (s.attempts >= MAX_ATTEMPTS) throw new TooManyRequestsError('Too many wrong codes. Start again.', 'TRIAL_LOCKED');
  if (s.expiresAt.getTime() < now.getTime()) throw new BadRequestError('That code has expired. Ask for a new one.', 'OTP_EXPIRED');
  if (!sameHash(s.codeHash, hashCode(id, code.trim()))) {
    const after = await prismaUnscoped.trialSignup.update({ where: { id }, data: { attempts: { increment: 1 } }, select: { attempts: true } });
    const left = MAX_ATTEMPTS - after.attempts;
    throw new BadRequestError(left > 0 ? `That code is not right. ${left} ${left === 1 ? 'try' : 'tries'} left.` : 'Too many wrong codes. Start again.', left > 0 ? 'OTP_INVALID' : 'TRIAL_LOCKED');
  }
  const p = s.data as unknown as Pending;
  // Someone may have taken the email or phone since the code went out.
  await assertNew(s.email, s.phoneKey);
  // Claim the signup so a double click cannot create two hostels.
  const claimed = await prismaUnscoped.trialSignup.updateMany({ where: { id, completedAt: null }, data: { completedAt: now } });
  if (claimed.count !== 1) throw new ConflictError('This trial is already being set up. Sign in with your email and password.', 'TRIAL_IN_PROGRESS');

  let created: Awaited<ReturnType<typeof createTenantWithAdmin>>;
  try {
    const planId = await trialPlan(p.rooms * p.bedsPerRoom);
    created = await createTenantWithAdmin(
      {
        name: p.hostelName,
        kind: p.kind === 'DORMITORY' ? TenantKind.DORMITORY : TenantKind.HOSTEL,
        ...(planId ? { planId } : {}),
        hostelAdmin: { name: s.name, email: s.email, phone: p.phone, password: 'unused-hashed-already' },
        property: { name: p.hostelName, city: p.city, ...(p.state ? { state: p.state as never } : {}), plannedRooms: p.rooms },
        access: { kind: 'TRIAL', trialDays: TRIAL_DAYS },
      },
      null,
      { passwordHash: s.passwordHash },
    );
    await buildRooms(created.tenant.id, created.property.id, p);
  } catch (e) {
    // Nothing usable was made; let them try again.
    await prismaUnscoped.trialSignup.update({ where: { id }, data: { completedAt: null } }).catch(() => {});
    throw e;
  }
  const tenantId = created.tenant.id;
  await prismaUnscoped.trialSignup.update({ where: { id }, data: { tenantId } });
  const beds = p.rooms * p.bedsPerRoom;
  const endsOn = created.tenant.access.endsOn;

  // The CRM side must never cost the owner their new account.
  try {
    await linkToCrm({ name: s.name, email: s.email, p, tenantId, beds, endsOn, now });
  } catch (e) {
    // eslint-disable-next-line no-console
    console.error(`[trial] CRM link failed for tenant ${tenantId}: ${e instanceof Error ? e.message : String(e)}`);
  }

  const welcome = trialWelcomeEmail({ name: s.name, hostelName: p.hostelName, email: s.email, endsOn: endsOn ? fmtDay(endsOn) : `${TRIAL_DAYS} days from today`, signInUrl: `${publicWebUrl}/login`, rooms: p.rooms, beds });
  void sendEmail(s.email, welcome.subject, welcome.text, welcome.html).catch(() => {});

  const session = await signInNewAccount(created.hostelAdmin.id);
  return { ...session, trial: { tenantId, endsOn, rooms: p.rooms, beds } };
}

async function linkToCrm(x: { name: string; email: string; p: Pending; tenantId: string; beds: number; endsOn: string | null; now: Date }) {
  const meta: Record<string, string> = { trialEndsOn: x.endsOn ?? '' };
  if (x.p.page) meta.page = x.p.page;
  if (x.p.utmSource) meta.utmSource = x.p.utmSource;
  if (x.p.utmMedium) meta.utmMedium = x.p.utmMedium;
  if (x.p.utmCampaign) meta.utmCampaign = x.p.utmCampaign;
  const lead = await ingestLead(
    {
      name: x.name,
      phone: x.p.phone,
      email: x.email,
      hostelName: x.p.hostelName,
      type: x.p.kind,
      beds: x.beds,
      city: x.p.city,
      state: x.p.state ?? null,
      message: `Started a free ${TRIAL_DAYS}-day trial${x.endsOn ? ` (ends ${fmtDay(x.endsOn)})` : ''} with ${x.p.rooms} rooms and ${x.beds} beds.`,
      consent: x.p.consent,
      source: 'Trial signup',
      via: 'Free trial signup',
      // Their welcome email is the first message.
      firstTouch: false,
      meta,
    },
    x.now,
  );
  await prismaUnscoped.crmContact.update({ where: { id: lead.contactId }, data: { tenantId: x.tenantId } });
  await openTrialDeal({
    contactId: lead.contactId,
    tenantId: x.tenantId,
    title: `${x.p.hostelName} — free trial`,
    companyName: x.p.hostelName,
    beds: x.beds,
    value: x.beds * BED_PRICE_YEAR,
    assigneeId: lead.ownerId,
    nextActionAt: lead.dueAt,
    endsOn: x.endsOn ? fmtDay(x.endsOn) : null,
  });
}
