import { randomBytes } from 'node:crypto';
import { PassStatus, Role } from '@prisma/client';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { inBackground, notifyPassDecided } from '../notifications/notifications.service';
import { hashPassword } from '../../lib/password';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { sendEmail } from '../../lib/email';
import { guardianInviteEmail } from '../../lib/email-templates';
import { currentBrand } from '../../lib/email-brand';
import { publicPass } from './gate.service';

/**
 * Guardians (Sprint 5): a parent's own login, scoped to one or more
 * students. They read what the student reads — dues, receipts, attendance,
 * passes, notices, settlement — and approve or decline a pass when the
 * hostel requires it. Created by the office from the student's page.
 */

/** Every student this guardian may see. The scope check for every guardian route. */
export async function studentsForGuardian(userId: string) {
  const links = await db.guardianLink.findMany({
    where: { userId },
    include: { student: { include: { user: { select: { name: true, email: true } }, bed: { include: { room: { select: { number: true } } } }, property: { select: { id: true, name: true, guardianApprovesPasses: true } } } } },
    orderBy: { invitedAt: 'asc' },
  });
  return links.map((l) => ({ id: l.student.id, name: l.student.user.name, email: l.student.user.email, room: l.student.bed ? `Room ${l.student.bed.room.number} · Bed ${l.student.bed.label}` : null, property: l.student.property, relation: l.relation, residencyStatus: l.student.residencyStatus }));
}

export async function assertGuardianOf(userId: string, studentProfileId: string) {
  const link = await db.guardianLink.findFirst({ where: { userId, studentProfileId }, select: { id: true } });
  if (!link) throw new NotFoundError('Student not found');
}

/**
 * Add a guardian to a student: an existing GUARDIAN account by email is
 * linked; otherwise a new one is created with a one-time password that is
 * emailed and returned once to the office (as device keys are).
 */
export async function addGuardian(studentProfileId: string, input: { name: string; email: string; phone?: string; relation?: string }, createdById: string) {
  const tenantId = getTenantIdOrThrow();
  const student = await db.studentProfile.findFirst({ where: { id: studentProfileId }, include: { user: { select: { name: true } }, property: { select: { name: true } } } });
  if (!student) throw new NotFoundError('Student not found');
  const email = input.email.trim().toLowerCase();
  let user = await db.user.findFirst({ where: { email } });
  let temporaryPassword: string | null = null;
  if (user && user.role !== Role.GUARDIAN) throw new ConflictError('That email already belongs to a HostelCare account that is not a guardian');
  if (user && user.tenantId !== tenantId) throw new ConflictError('That guardian belongs to another hostel');
  if (!user) {
    temporaryPassword = `G-${randomBytes(6).toString('base64url')}`;
    user = await db.user.create({ data: { role: Role.GUARDIAN, name: input.name.trim(), email, phone: input.phone?.trim() ?? null, passwordHash: await hashPassword(temporaryPassword), createdById } });
  }
  const existing = await db.guardianLink.findFirst({ where: { userId: user.id, studentProfileId } });
  if (existing) throw new ConflictError('This guardian is already linked to the student');
  const link = await db.guardianLink.create({ data: { tenantId, userId: user.id, studentProfileId, relation: input.relation?.trim() ?? null } });
  const brand = await currentBrand(student.property?.name);
  const mail = guardianInviteEmail({ firm: brand.firm, brand, guardianName: user.name, studentName: student.user.name, email, temporaryPassword });
  const sent = await sendEmail(email, mail.subject, mail.text, mail.html).catch(() => ({ sent: false, mode: 'error' as const }));
  return { guardian: { id: user.id, linkId: link.id, name: user.name, email: user.email, phone: user.phone, relation: link.relation, invitedAt: link.invitedAt }, temporaryPassword, emailed: sent.sent || sent.mode === 'log' };
}

export async function listGuardians(studentProfileId: string) {
  const links = await db.guardianLink.findMany({ where: { studentProfileId }, include: { user: { select: { id: true, name: true, email: true, phone: true } } }, orderBy: { invitedAt: 'asc' } });
  return links.map((l) => ({ id: l.user.id, linkId: l.id, name: l.user.name, email: l.user.email, phone: l.user.phone, relation: l.relation, invitedAt: l.invitedAt }));
}

/** Unlink; the account itself is removed when it has no students left. */
export async function removeGuardian(studentProfileId: string, linkId: string) {
  const link = await db.guardianLink.findFirst({ where: { id: linkId, studentProfileId } });
  if (!link) throw new NotFoundError('Guardian link not found');
  await db.guardianLink.delete({ where: { id: linkId } });
  const left = await db.guardianLink.count({ where: { userId: link.userId } });
  if (left === 0) await db.user.delete({ where: { id: link.userId } }).catch(() => {});
  return { removed: true, accountDeleted: left === 0 };
}

// ── Guardian actions ─────────────────────────────────────────────────────────

export async function guardianPasses(userId: string, studentProfileId: string) {
  await assertGuardianOf(userId, studentProfileId);
  const rows = await db.gatePass.findMany({
    where: { studentProfileId },
    include: { student: { include: { user: { select: { id: true, name: true, email: true, phone: true } }, bed: { include: { room: { select: { number: true, floor: true } } } } } }, request: { select: { id: true, subject: true, body: true, status: true, fromDate: true, toDate: true } } },
    orderBy: { validFrom: 'desc' },
    take: 20,
  });
  return rows.map((p) => ({ ...publicPass(p), reason: p.request?.body ?? p.purpose ?? null, subject: p.request?.subject ?? 'Quick outing' }));
}

export async function decidePass(userId: string, passId: string, approve: boolean, note?: string) {
  const pass = await db.gatePass.findFirst({ where: { id: passId }, include: { student: { include: { user: { select: { id: true, name: true, email: true, phone: true } }, bed: { include: { room: { select: { number: true, floor: true } } } } } } } });
  if (!pass) throw new NotFoundError('Pass not found');
  await assertGuardianOf(userId, pass.studentProfileId);
  if (pass.status !== PassStatus.PENDING_GUARDIAN) throw new ConflictError(`This pass is ${pass.status.toLowerCase().replace('_', ' ')}, not waiting for you`);
  if (!approve && !note?.trim()) throw new BadRequestError('Say why you are declining, so the student and the warden know');
  const updated = await db.gatePass.update({
    where: { id: passId },
    data: approve ? { status: PassStatus.ACTIVE, guardianApprovedAt: new Date(), guardianNote: note?.slice(0, 300) ?? null } : { status: PassStatus.DECLINED, guardianDeclinedAt: new Date(), guardianNote: note!.slice(0, 300) },
    include: { student: { include: { user: { select: { id: true, name: true, email: true, phone: true } }, bed: { include: { room: { select: { number: true, floor: true } } } } } } },
  });
  const tenantId = getTenantIdOrThrow();
  inBackground('push: pass decided', () => notifyPassDecided(tenantId, passId));
  return publicPass(updated);
}
