import { randomBytes } from 'node:crypto';
import { AccountInviteKind, OtpPurpose, Prisma, Role } from '@prisma/client';
import { prismaUnscoped as db } from '../../lib/prisma';
import { env, publicWebUrl } from '../../config/env';
import { hashPassword } from '../../lib/password';
import { emailFailed, isEmailConfigured, sendEmail, type EmailMode } from '../../lib/email';
import { bugTrackerInviteEmail } from '../../lib/email-templates';
import { ConflictError, NotFoundError, ServiceUnavailableError } from '../../lib/errors';
import { issueInvite } from '../crm/crm-invites.service';
import { TRACKER_ROLES, type BugActor, type TrackerRole } from './bug-access';

/**
 * The bug tracker's team, managed by the SUPER_ADMIN (docs/bug-tracker-plan.md, D2/D3).
 *
 * A tester or developer is a User with role QA or DEVELOPER and no tenant,
 * exactly like a CRM user: invited, never handed a password; always an emailed
 * code at sign-in; switching one off ends their sessions at once. Every query
 * is pinned to those two roles, so these endpoints never reach anyone else.
 * The invite links are the CRM's (AccountInvite), opened on /bugs/invite/.
 */

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

const select = {
  id: true,
  name: true,
  email: true,
  phone: true,
  role: 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 }>;

const activated = (u: Row) => !!u.lastLoginAt || u.accountInvites.some((i) => i.usedAt);
const wordFor = (role: Role) => (role === Role.QA ? 'tester' : 'developer');

function shape(u: Row) {
  const pending = u.accountInvites.find((i) => !i.usedAt) ?? null;
  const status: MemberStatus = u.deactivatedAt ? 'DEACTIVATED' : activated(u) ? 'ACTIVE' : 'INVITED';
  return {
    id: u.id,
    name: u.name,
    email: u.email,
    phone: u.phone,
    role: u.role as TrackerRole,
    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,
  };
}

async function load(id: string): Promise<Row> {
  const u = await db.user.findFirst({ where: { id, role: { in: [...TRACKER_ROLES] } }, select });
  if (!u) throw new NotFoundError('Team member not found.');
  return u;
}

export async function listMembers(filters: { q?: string; status?: MemberStatus; role?: TrackerRole }) {
  const q = filters.q?.trim();
  const rows = await db.user.findMany({
    where: {
      role: filters.role ?? { in: [...TRACKER_ROLES] },
      ...(filters.status === 'DEACTIVATED' ? { deactivatedAt: { not: null } } : filters.status ? { deactivatedAt: null } : {}),
      ...(q ? { OR: [{ name: { contains: q, mode: 'insensitive' } }, { email: { contains: q, mode: 'insensitive' } }] } : {}),
    },
    orderBy: { name: 'asc' },
    take: 500,
    select,
  });
  return { members: rows.map(shape).filter((u) => !filters.status || u.status === filters.status) };
}

function assertCanEmail() {
  if (isEmailConfigured() || 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;
}

const inviteUrl = (token: string) => `${publicWebUrl}/bugs/invite/${token}`;

async function deliverLink(user: { id: string; name: string; email: string; role: Role }, kind: AccountInviteKind, actor: BugActor): Promise<LinkDelivery> {
  const { token, expiresAt, hours } = await issueInvite(db, user.id, kind, actor.id);
  const url = inviteUrl(token);
  const mail = bugTrackerInviteEmail({ name: user.name, inviterName: actor.name, url, hours, kind, as: wordFor(user.role) });
  const result = await sendEmail(user.email, mail.subject, mail.text, mail.html);
  if (result.mode === 'log') {
    // eslint-disable-next-line no-console
    console.log(`[bugs dry-run] ${kind} link for ${user.email}: ${url}`);
  }
  return { sent: !emailFailed(result), mode: result.mode, kind, expiresAt, ...(env.AUTH_OTP_ECHO ? { devUrl: url } : {}) };
}

export async function createMember(input: { name: string; email: string; phone?: string | null; role: TrackerRole }, actor: BugActor) {
  assertCanEmail();
  if (await db.user.findUnique({ where: { email: input.email }, select: { id: true } })) {
    throw new ConflictError('That email is already registered on HostelCare.', 'EMAIL_TAKEN');
  }
  const now = new Date();
  const created = await db.user.create({
    data: {
      role: input.role,
      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, role: true },
  });
  const delivery = await deliverLink(created, AccountInviteKind.INVITE, actor);
  return { member: shape(await load(created.id)), delivery };
}

export async function updateMember(id: string, input: { name?: string; email?: string; phone?: string; role?: TrackerRole }) {
  const before = await load(id);
  const emailChanged = input.email !== undefined && input.email !== before.email;
  const roleChanged = input.role !== undefined && input.role !== before.role;
  if (emailChanged && (await db.user.findUnique({ where: { email: input.email }, select: { id: true } }))) {
    throw new ConflictError('That email is already registered on HostelCare.', 'EMAIL_TAKEN');
  }
  await db.$transaction(async (tx) => {
    await tx.user.update({
      where: { id },
      data: {
        ...(input.name !== undefined ? { name: input.name } : {}),
        ...(input.phone !== undefined ? { phone: input.phone || null } : {}),
        ...(emailChanged ? { email: input.email } : {}),
        ...(roleChanged ? { role: input.role } : {}),
        // Sign-in codes go to the email, and a session carries the role it was
        // opened with: a new address or a new role ends every session.
        ...(emailChanged || roleChanged ? { 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 } });
    }
    // No longer a developer: no module sends its new bugs to them.
    if (roleChanged && before.role === Role.DEVELOPER) {
      await tx.bugModule.updateMany({ where: { defaultDeveloperId: id }, data: { defaultDeveloperId: null } });
    }
  });
  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: BugActor) {
  const u = await load(id);
  if (u.deactivatedAt) throw new ConflictError('Switch the account back on before sending a link.', 'ACCOUNT_DEACTIVATED');
  assertCanEmail();
  const delivery = await deliverLink(u, activated(u) ? AccountInviteKind.RESET : AccountInviteKind.INVITE, actor);
  return { member: shape(await load(id)), delivery };
}

export async function deactivateMember(id: string) {
  const u = await load(id);
  if (u.deactivatedAt) return shape(u);
  const now = new Date();
  await db.$transaction([
    db.user.update({ where: { id }, data: { deactivatedAt: now, sessionsRevokedAt: now } }),
    db.emailOtp.updateMany({ where: { userId: id, purpose: OtpPurpose.LOGIN, consumedAt: null }, data: { consumedAt: now } }),
    db.accountInvite.deleteMany({ where: { userId: id, usedAt: null } }),
    // A switched-off developer no longer receives a module's new bugs.
    db.bugModule.updateMany({ where: { defaultDeveloperId: id }, data: { defaultDeveloperId: null } }),
  ]);
  return shape(await load(id));
}

export async function reactivateMember(id: string) {
  const u = await load(id);
  if (!u.deactivatedAt) return shape(u);
  await db.user.update({ where: { id }, data: { deactivatedAt: null } });
  return shape(await load(id));
}

export async function signOutEverywhere(id: string) {
  await load(id);
  await db.user.update({ where: { id }, data: { sessionsRevokedAt: new Date() } });
  return shape(await load(id));
}

/** Who is on the tracker and switched on: the people a bug can be assigned to or mention. */
export async function activeMembers() {
  return db.user.findMany({
    where: { role: { in: [Role.SUPER_ADMIN, ...TRACKER_ROLES] }, deactivatedAt: null },
    orderBy: { name: 'asc' },
    select: { id: true, name: true, role: true },
  });
}
