import { createHash } from 'node:crypto';
import { Prisma, Role } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';
import { publicWebUrl } from '../../config/env';
import { emailFailed, sendEmail, type EmailAttachment } from '../../lib/email';
import { crmEmail, type EmailMessage } from '../../lib/email-templates';
import { getCrmSettings, superAdminCopyAddress } from './crm-settings.service';

/**
 * How CRM email leaves: once, logged, and copied to the super admin.
 *
 * Every send first claims a CrmEmailLog row under a unique key; if the row
 * already exists the email has been sent (or is being sent) and nothing
 * happens. The master switch in CRM settings stops everything here, in one
 * place. The super admin's copy is its own logged send.
 */

export const crmUrl = (hash: string) => `${publicWebUrl}/crm#${hash}`;
export const manageUrl = () => crmUrl('profile');

// ── India time ─────────────────────────────────────────────────────────────

const IST_MS = 330 * 60 * 1000;

/** The calendar day, hour and weekday in India for an instant. */
export function ist(now: Date) {
  const s = new Date(now.getTime() + IST_MS);
  return {
    date: s.toISOString().slice(0, 10),
    hour: s.getUTCHours(),
    minute: s.getUTCMinutes(),
    weekday: s.getUTCDay(), // 0 = Sunday
  };
}

/** The instant of hh:00 India time on the India date `date` (YYYY-MM-DD). */
export function istAt(date: string, hour: number) {
  return new Date(Date.parse(`${date}T00:00:00Z`) + hour * 3_600_000 - IST_MS);
}

export function istDayStart(now: Date) {
  return istAt(ist(now).date, 0);
}

export const fmtIst = (d: Date) =>
  d.toLocaleString('en-IN', { timeZone: 'Asia/Kolkata', day: 'numeric', month: 'short', hour: 'numeric', minute: '2-digit' });
export const fmtIstTime = (d: Date) => d.toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata', hour: 'numeric', minute: '2-digit' });
export const fmtIstDay = (d: Date) => d.toLocaleDateString('en-IN', { timeZone: 'Asia/Kolkata', weekday: 'short', day: 'numeric', month: 'short' });
export const rupees = (n: number) => `₹${n.toLocaleString('en-IN')}`;

// ── Members and their preferences ──────────────────────────────────────────

export interface Prefs {
  alerts: boolean;
  allActivity: boolean;
  followUps: boolean;
  tasks: boolean;
  daily: boolean;
  weekly: boolean;
  summaryHour: number;
}

export const DEFAULT_PREFS: Prefs = { alerts: true, allActivity: false, followUps: true, tasks: true, daily: true, weekly: true, summaryHour: 9 };

export interface Member {
  id: string;
  name: string;
  email: string;
  role: Role;
  prefs: Prefs;
}

/**
 * Everyone who can open the CRM, is switched on, and has signed in at least
 * once (an invited user who never came in gets no CRM email), with their
 * email preferences.
 */
export async function crmMembersWithPrefs(): Promise<Member[]> {
  const rows = await prismaUnscoped.user.findMany({
    where: { role: { in: [Role.CRM_USER, Role.SUPER_ADMIN] }, deactivatedAt: null, OR: [{ role: Role.SUPER_ADMIN }, { lastLoginAt: { not: null } }] },
    select: { id: true, name: true, email: true, role: true, crmNotificationPref: true },
  });
  return rows.map((r) => {
    const p = r.crmNotificationPref;
    return { id: r.id, name: r.name, email: r.email, role: r.role, prefs: p ? { alerts: p.alerts, allActivity: p.allActivity, followUps: p.followUps, tasks: p.tasks, daily: p.daily, weekly: p.weekly, summaryHour: p.summaryHour } : { ...DEFAULT_PREFS } };
  });
}

export async function getPrefs(userId: string): Promise<Prefs> {
  const p = await prismaUnscoped.crmNotificationPref.findUnique({ where: { userId } });
  return p ? { alerts: p.alerts, allActivity: p.allActivity, followUps: p.followUps, tasks: p.tasks, daily: p.daily, weekly: p.weekly, summaryHour: p.summaryHour } : { ...DEFAULT_PREFS };
}

export async function setPrefs(userId: string, input: Partial<Prefs>) {
  await prismaUnscoped.crmNotificationPref.upsert({ where: { userId }, update: input, create: { userId, ...DEFAULT_PREFS, ...input } });
  return getPrefs(userId);
}

// ── Sending ────────────────────────────────────────────────────────────────

export type SendStatus = 'SENT' | 'DRY_RUN' | 'FAILED' | 'SKIPPED' | 'DUPLICATE';

/** Send one email at most once per key. */
export async function deliver(p: {
  key: string;
  kind: string;
  to: string;
  userId?: string | null;
  mail: EmailMessage;
  isCopy?: boolean;
  /** A person confirmed this exact email: send even with CRM notifications off. */
  force?: boolean;
  replyTo?: string;
  /** A calendar invite and the like. */
  attachments?: EmailAttachment[];
}): Promise<SendStatus> {
  try {
    await prismaUnscoped.crmEmailLog.create({
      data: { key: p.key, kind: p.kind, userId: p.userId ?? null, toEmail: p.to, subject: p.mail.subject.slice(0, 300), isCopy: !!p.isCopy, status: 'PENDING' },
    });
  } catch (e) {
    if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') return 'DUPLICATE';
    throw e;
  }
  const settings = await getCrmSettings();
  if (!settings.emailsEnabled && !p.force) {
    await prismaUnscoped.crmEmailLog.update({ where: { key: p.key }, data: { status: 'SKIPPED', error: 'CRM emails are switched off' } });
    return 'SKIPPED';
  }
  const result = await sendEmail(p.to, p.mail.subject, p.mail.text, p.mail.html, p.attachments ?? [], p.replyTo ? { replyTo: p.replyTo } : {});
  const status: SendStatus = result.mode === 'log' ? 'DRY_RUN' : emailFailed(result) ? 'FAILED' : result.sent ? 'SENT' : 'SKIPPED';
  await prismaUnscoped.crmEmailLog.update({ where: { key: p.key }, data: { status, ...(status === 'FAILED' ? { error: result.mode } : {}) } });
  return status;
}

/**
 * Send to a member and copy the super admin. `build(copyFor)` makes the
 * email; for the copy it is told whose email it copies.
 */
export async function deliverWithCopy(p: {
  key: string;
  kind: string;
  member: { id: string; email: string; name: string };
  build: (copyFor?: string) => EmailMessage;
  actorEmail?: string | null;
  /** When several members get the same reminder, one copy is enough: give them one copy key. */
  copyKey?: string;
  /** No copy at all — the super admin already gets this one in their own name. */
  noCopy?: boolean;
}) {
  const status = await deliver({ key: p.key, kind: p.kind, to: p.member.email, userId: p.member.id, mail: p.build() });
  if (status === 'DUPLICATE' || p.noCopy) return status;
  const copy = await superAdminCopyAddress({ actorEmail: p.actorEmail, recipients: [p.member.email] });
  if (copy) await deliver({ key: p.copyKey ?? `${p.key}:copy`, kind: p.kind, to: copy, mail: p.build(`${p.member.name} (${p.member.email})`), isCopy: true });
  return status;
}

export async function emailLog(limit = 50, kind?: string) {
  return prismaUnscoped.crmEmailLog.findMany({ where: kind ? { kind } : {}, orderBy: { createdAt: 'desc' }, take: Math.min(limit, 200) });
}

// ── New-device sign-in ─────────────────────────────────────────────────────

/** "Chrome on macOS" from a user-agent string — enough for a person to recognise. */
export function deviceLabel(ua: string): string {
  const browser = /Edg\//.test(ua) ? 'Edge' : /OPR\//.test(ua) ? 'Opera' : /Firefox\//.test(ua) ? 'Firefox' : /Chrome\//.test(ua) ? 'Chrome' : /Safari\//.test(ua) ? 'Safari' : 'a browser';
  const os = /iPhone|iPad/.test(ua) ? 'iOS' : /Android/.test(ua) ? 'Android' : /Mac OS X/.test(ua) ? 'macOS' : /Windows/.test(ua) ? 'Windows' : /Linux/.test(ua) ? 'Linux' : 'an unknown system';
  return `${browser} on ${os}`;
}

/**
 * After a CRM user signs in: remember the browser, and if it is one they
 * have not used before (and not their very first), tell them — and the
 * super admin.
 */
export async function noteSignIn(userId: string, userAgent: string | undefined, ip: string | undefined, now = new Date()) {
  try {
    const ua = (userAgent ?? 'unknown').slice(0, 400);
    const fingerprint = createHash('sha256').update(ua).digest('hex');
    const label = deviceLabel(ua);
    const [user, known, count] = await Promise.all([
      prismaUnscoped.user.findUnique({ where: { id: userId }, select: { id: true, name: true, email: true, role: true } }),
      prismaUnscoped.crmKnownDevice.findUnique({ where: { userId_fingerprint: { userId, fingerprint } } }),
      prismaUnscoped.crmKnownDevice.count({ where: { userId } }),
    ]);
    if (!user || user.role !== Role.CRM_USER) return;
    if (known) {
      await prismaUnscoped.crmKnownDevice.update({ where: { id: known.id }, data: { lastSeenAt: now } });
      return;
    }
    const device = await prismaUnscoped.crmKnownDevice.create({ data: { userId, fingerprint, label, firstSeenAt: now, lastSeenAt: now } });
    if (count === 0) return; // their first browser: nothing to compare with
    await deliverWithCopy({
      key: `device:${device.id}`,
      kind: 'NEW_DEVICE',
      member: user,
      build: (copyFor) =>
        crmEmail({
          title: 'New sign-in to your CRM account',
          intro: `${user.name}, your HostelCare CRM account was just signed in to from ${label}. If this was you, there is nothing to do.`,
          badge: 'Security',
          tone: 'warning',
          sections: [
            {
              heading: 'Sign-in',
              items: [
                { text: label, sub: ip ? `Network address ${ip}` : null, aside: fmtIst(now) },
              ],
            },
          ],
          reason: 'If this was not you, change your password from your profile and tell the super admin, who can sign you out everywhere.',
          cta: { label: 'Open my profile', url: manageUrl() },
          copyFor,
        }),
    });
  } catch (err) {
    // eslint-disable-next-line no-console
    console.error(`[crm] new-device check failed: ${err instanceof Error ? err.message : String(err)}`);
  }
}
