import { randomBytes } from 'node:crypto';
import { AccountInviteKind, OtpPurpose, Prisma, Role } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';
import { env } from '../../config/env';
import { hashPassword } from '../../lib/password';
import { emailFailed, isEmailConfigured, sendEmail, type EmailMode } from '../../lib/email';
import { crmInviteEmail, crmNoticeEmail } from '../../lib/email-templates';
import { ConflictError, NotFoundError, ServiceUnavailableError } from '../../lib/errors';
import { inviteUrl, issueInvite } from './crm-invites.service';
import { superAdminCopyAddress } from './crm-settings.service';

/**
 * The platform's sales and marketing team, managed by the SUPER_ADMIN.
 *
 * A CRM user is a User with role CRM_USER and no tenant. They are invited,
 * never handed a password; they always sign in with an emailed code; and
 * switching one off ends their sessions at once. Their records stay when
 * they are switched off.
 *
 * Platform-level data: every query here uses the unscoped client and is
 * pinned to role CRM_USER, so these endpoints can never reach a hostel's
 * staff or students.
 */

export type CrmUserStatus = 'INVITED' | 'ACTIVE' | 'DEACTIVATED';

export interface Actor {
  id: string;
  name: string;
  email: string;
}

const select = {
  id: true,
  name: true,
  email: true,
  phone: true,
  createdAt: true,
  lastLoginAt: true,
  deactivatedAt: true,
  accountInvites: { orderBy: { createdAt: 'desc' }, select: { kind: true, expiresAt: true, usedAt: true, createdAt: true } },
} satisfies Prisma.UserSelect;

type Row = Prisma.UserGetPayload<{ select: typeof select }>;

/** Signed in at least once, or has set a password from a link. */
const activated = (u: Row) => !!u.lastLoginAt || u.accountInvites.some((i) => i.usedAt);

function shape(u: Row) {
  const pending = u.accountInvites.find((i) => !i.usedAt) ?? null;
  const status: CrmUserStatus = u.deactivatedAt ? 'DEACTIVATED' : activated(u) ? 'ACTIVE' : 'INVITED';
  return {
    id: u.id,
    name: u.name,
    email: u.email,
    phone: u.phone,
    status,
    createdAt: u.createdAt,
    lastLoginAt: u.lastLoginAt,
    deactivatedAt: u.deactivatedAt,
    pendingLink: pending
      ? { kind: pending.kind, sentAt: pending.createdAt, expiresAt: pending.expiresAt, expired: pending.expiresAt.getTime() < Date.now() }
      : null,
  };
}

export type CrmUser = ReturnType<typeof shape>;

async function load(id: string): Promise<Row> {
  const u = await prismaUnscoped.user.findFirst({ where: { id, role: Role.CRM_USER }, select });
  if (!u) throw new NotFoundError('CRM user not found');
  return u;
}

export async function listCrmUsers(filters: { search?: string; status?: CrmUserStatus }) {
  const q = filters.search?.trim();
  const rows = await prismaUnscoped.user.findMany({
    where: {
      role: Role.CRM_USER,
      ...(filters.status === 'DEACTIVATED' ? { deactivatedAt: { not: null } } : filters.status ? { deactivatedAt: null } : {}),
      ...(q
        ? {
            OR: [
              { name: { contains: q, mode: 'insensitive' } },
              { email: { contains: q, mode: 'insensitive' } },
              { phone: { contains: q } },
            ],
          }
        : {}),
    },
    orderBy: { name: 'asc' },
    take: 500,
    select,
  });
  const users = rows.map(shape).filter((u) => !filters.status || u.status === filters.status);
  return { users };
}

/** In production an invite nobody can receive is a dead account; refuse up front. */
function assertCanEmail() {
  if (isEmailConfigured()) return;
  if (env.NODE_ENV === 'development' || env.NODE_ENV === 'test') return;
  throw new ServiceUnavailableError(
    'Email delivery is not configured on this server, so the invite cannot be sent.',
    'EMAIL_NOT_CONFIGURED',
  );
}

export interface LinkDelivery {
  sent: boolean;
  mode: EmailMode;
  kind: AccountInviteKind;
  expiresAt: Date;
  /** Development only (AUTH_OTP_ECHO): the link itself, so tests can follow it. */
  devUrl?: string;
}

/**
 * Email the link to its owner, then tell the super admin's copy address that
 * a link went out — without the link, which is the owner's alone.
 */
async function deliverLink(user: { id: string; name: string; email: string }, kind: AccountInviteKind, actor: Actor): Promise<LinkDelivery> {
  const { token, expiresAt, hours } = await issueInvite(prismaUnscoped, user.id, kind, actor.id);
  const url = inviteUrl(token);
  const mail = crmInviteEmail({ name: user.name, inviterName: actor.name, url, hours, kind });
  const result = await sendEmail(user.email, mail.subject, mail.text, mail.html);
  if (result.mode === 'log') {
    // eslint-disable-next-line no-console
    console.log(`[crm dry-run] ${kind} link for ${user.email}: ${url}`);
  }
  void notifyCopy(actor, user.email, {
    title: kind === AccountInviteKind.INVITE ? `Invite sent to ${user.name}` : `Password link sent to ${user.name}`,
    intro: `${actor.name} sent ${user.name} a link to ${kind === AccountInviteKind.INVITE ? 'join the CRM' : 'set a new password'}.`,
    rows: [
      ['CRM user', `${user.name} (${user.email})`],
      ['Sent by', actor.name],
      ['Link expires', expiresAt.toUTCString()],
    ],
  });
  return {
    sent: !emailFailed(result),
    mode: result.mode,
    kind,
    expiresAt,
    ...(env.AUTH_OTP_ECHO ? { devUrl: url } : {}),
  };
}

/** The super admin's copy of a CRM event. Fire-and-forget: never blocks the response. */
async function notifyCopy(actor: Actor, subjectEmail: string, notice: { title: string; intro: string; rows: [string, string][] }) {
  try {
    const to = await superAdminCopyAddress({ actorEmail: actor.email, recipients: [subjectEmail] });
    if (!to) return;
    const mail = crmNoticeEmail(notice);
    await sendEmail(to, mail.subject, mail.text, mail.html);
  } catch (err) {
    // eslint-disable-next-line no-console
    console.error(`CRM copy email failed: ${err instanceof Error ? err.message : String(err)}`);
  }
}

export async function createCrmUser(input: { name: string; email: string; phone?: string | null }, actor: Actor) {
  assertCanEmail();
  const taken = await prismaUnscoped.user.findUnique({ where: { email: input.email }, select: { id: true } });
  if (taken) throw new ConflictError('That email is already registered on HostelCare.', 'EMAIL_TAKEN');

  const now = new Date();
  const created = await prismaUnscoped.user.create({
    data: {
      role: Role.CRM_USER,
      tenantId: null,
      name: input.name,
      email: input.email,
      phone: input.phone || null,
      // A password nobody knows: the account opens only through the invite.
      passwordHash: await hashPassword(randomBytes(32).toString('base64url')),
      twoFactorEnabled: true,
      twoFactorEnabledAt: now,
      createdById: actor.id,
    },
    select: { id: true, name: true, email: true },
  });
  const delivery = await deliverLink(created, AccountInviteKind.INVITE, actor);
  return { user: shape(await load(created.id)), delivery };
}

export async function updateCrmUser(id: string, input: { name?: string; email?: string; phone?: string }, actor: Actor) {
  const before = await load(id);
  const emailChanged = input.email !== undefined && input.email !== before.email;
  if (emailChanged) {
    const taken = await prismaUnscoped.user.findUnique({ where: { email: input.email }, select: { id: true } });
    if (taken) throw new ConflictError('That email is already registered on HostelCare.', 'EMAIL_TAKEN');
  }
  await prismaUnscoped.$transaction(async (tx) => {
    await tx.user.update({
      where: { id },
      data: {
        ...(input.name !== undefined ? { name: input.name } : {}),
        ...(input.phone !== undefined ? { phone: input.phone || null } : {}),
        // Sign-in codes go to the email, so a new address ends every session
        // and every half-finished sign-in, and voids links sent to the old one.
        ...(emailChanged ? { email: input.email, sessionsRevokedAt: new Date() } : {}),
      },
    });
    if (emailChanged) {
      await tx.emailOtp.updateMany({ where: { userId: id, consumedAt: null }, data: { consumedAt: new Date() } });
      await tx.accountInvite.deleteMany({ where: { userId: id, usedAt: null } });
    }
  });
  if (emailChanged) {
    void notifyCopy(actor, input.email!, {
      title: `Email changed for ${before.name}`,
      intro: `${actor.name} changed the sign-in email of ${before.name}. Their sessions were ended.`,
      rows: [
        ['Old email', before.email],
        ['New email', input.email!],
        ['Changed by', actor.name],
      ],
    });
  }
  return shape(await load(id));
}

/** A first-password invite for someone who never got in; a reset link for anyone else. */
export async function sendPasswordLink(id: string, actor: Actor) {
  const u = await load(id);
  if (u.deactivatedAt) throw new ConflictError('Switch the account back on before sending a link.', 'ACCOUNT_DEACTIVATED');
  assertCanEmail();
  const kind = activated(u) ? AccountInviteKind.RESET : AccountInviteKind.INVITE;
  const delivery = await deliverLink(u, kind, actor);
  return { user: shape(await load(id)), delivery };
}

export async function deactivateCrmUser(id: string, actor: Actor) {
  const u = await load(id);
  if (u.deactivatedAt) return shape(u);
  const now = new Date();
  await prismaUnscoped.$transaction([
    prismaUnscoped.user.update({ where: { id }, data: { deactivatedAt: now, sessionsRevokedAt: now } }),
    prismaUnscoped.emailOtp.updateMany({ where: { userId: id, purpose: OtpPurpose.LOGIN, consumedAt: null }, data: { consumedAt: now } }),
    prismaUnscoped.accountInvite.deleteMany({ where: { userId: id, usedAt: null } }),
  ]);
  void notifyCopy(actor, u.email, {
    title: `${u.name} was switched off`,
    intro: `${actor.name} switched off the CRM account of ${u.name}. They were signed out everywhere.`,
    rows: [
      ['CRM user', `${u.name} (${u.email})`],
      ['Switched off by', actor.name],
    ],
  });
  return shape(await load(id));
}

export async function reactivateCrmUser(id: string, actor: Actor) {
  const u = await load(id);
  if (!u.deactivatedAt) return shape(u);
  await prismaUnscoped.user.update({ where: { id }, data: { deactivatedAt: null } });
  void notifyCopy(actor, u.email, {
    title: `${u.name} was switched back on`,
    intro: `${actor.name} switched the CRM account of ${u.name} back on.`,
    rows: [
      ['CRM user', `${u.name} (${u.email})`],
      ['Switched on by', actor.name],
    ],
  });
  return shape(await load(id));
}

/** End every session the user holds, without touching their password. */
export async function signOutEverywhere(id: string) {
  await load(id);
  await prismaUnscoped.user.update({ where: { id }, data: { sessionsRevokedAt: new Date() } });
  return shape(await load(id));
}

/** Who the CRM can assign work to: active CRM users plus the super admin(s). */
export async function crmMembers() {
  const rows = await prismaUnscoped.user.findMany({
    where: { role: { in: [Role.CRM_USER, Role.SUPER_ADMIN] }, deactivatedAt: null },
    orderBy: { name: 'asc' },
    select: { id: true, name: true, email: true, role: true },
  });
  return rows;
}
