import { BedStatus, EnquiryStatus, PricingMode, Role } from '@prisma/client';
import { db, prismaUnscoped } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { paginated, type Pagination } from '../../lib/pagination';
import { presignDownload } from '../uploads/uploads.service';
import { sendEmail } from '../../lib/email';
import { enquiryEmail } from '../../lib/email-templates';
import { brandForTenant } from '../../lib/email-brand';
import { inBackground } from '../notifications/notifications.service';

/**
 * The public vacancy page and the enquiries it produces (Sprint 6).
 *
 * The public side is keyed by a property's slug and nothing else: no tenant
 * id, no listing, no search. It reads through the unscoped client because
 * there is no signed-in user, so every query here names the property found
 * by slug explicitly. The admin side is ordinary scoped work.
 */

// ── Public ──────────────────────────────────────────────────────────────────

async function findPublic(slug: string) {
  const property = await prismaUnscoped.property.findFirst({
    where: { publicSlug: slug, publicEnabled: true, isArchived: false },
    select: { id: true, tenantId: true, name: true, city: true, state: true, address: true, logoUrl: true, publicDescription: true, publicPhone: true, amenities: true, photos: true, pricingMode: true },
  });
  if (!property) throw new NotFoundError('No such page');
  return property;
}

/** What a visitor sees: the building, its room types with free beds, and how to ask. */
export async function publicProperty(slug: string) {
  const p = await findPublic(slug);
  const [rooms, settings] = await Promise.all([
    prismaUnscoped.room.findMany({ where: { propertyId: p.id, archivedAt: null, floor: { not: null } }, select: { type: true, monthlyRent: true, beds: { where: { archivedAt: null }, select: { status: true, monthlyRent: true } } } }),
    prismaUnscoped.tenantSettings.findFirst({ where: { tenantId: p.tenantId }, select: { billingFirmName: true, billingAccentColor: true } }),
  ]);

  // Room types, each with how many beds are free and the lowest rent on offer.
  const types = new Map<string, { type: string; beds: number; vacant: number; rentFrom: number | null }>();
  for (const r of rooms) {
    const key = r.type?.trim() || 'Room';
    const t = types.get(key) ?? { type: key, beds: 0, vacant: 0, rentFrom: null };
    t.beds += r.beds.length;
    t.vacant += r.beds.filter((b) => b.status === BedStatus.VACANT).length;
    const rents = p.pricingMode === PricingMode.ROOM ? [r.monthlyRent] : r.beds.map((b) => b.monthlyRent);
    for (const rent of rents) if (rent && rent > 0 && (t.rentFrom == null || rent < t.rentFrom)) t.rentFrom = rent;
    types.set(key, t);
  }

  // Signed, short-lived URLs — the keys themselves never leave the server.
  const url = (key: string | null) => (key ? presignDownload(p.tenantId, key).catch(() => null) : Promise.resolve(null));
  const [logo, ...photos] = await Promise.all([url(p.logoUrl), ...p.photos.map((k) => url(k))]);

  return {
    slug,
    name: p.name,
    hostel: settings?.billingFirmName?.trim() || null,
    city: p.city,
    state: p.state,
    address: p.address,
    description: p.publicDescription,
    phone: p.publicPhone,
    amenities: p.amenities,
    accentColor: settings?.billingAccentColor ?? null,
    logoUrl: logo,
    photos: photos.filter((u): u is string => !!u),
    pricingMode: p.pricingMode,
    roomTypes: [...types.values()].sort((a, b) => (a.rentFrom ?? Infinity) - (b.rentFrom ?? Infinity)),
    vacantBeds: [...types.values()].reduce((n, t) => n + t.vacant, 0),
  };
}

/** A prospect's form. The admins are emailed in the background. */
export async function createEnquiry(slug: string, input: { name: string; phone: string; email?: string; roomType?: string; moveIn?: string; message?: string }) {
  const p = await findPublic(slug);
  const enquiry = await prismaUnscoped.enquiry.create({
    data: {
      tenantId: p.tenantId,
      propertyId: p.id,
      name: input.name,
      phone: input.phone,
      email: input.email,
      roomType: input.roomType,
      moveIn: input.moveIn ? new Date(`${input.moveIn}T00:00:00.000Z`) : undefined,
      message: input.message,
    },
  });
  inBackground('enquiry email', async () => {
    const admins = await prismaUnscoped.user.findMany({ where: { tenantId: p.tenantId, role: Role.HOSTEL_ADMIN, email: { not: '' } }, select: { email: true, name: true }, take: 5 });
    const brand = await brandForTenant(p.tenantId, p.name);
    const mail = enquiryEmail({ firm: p.name, brand, name: input.name, phone: input.phone, email: input.email ?? null, roomType: input.roomType ?? null, moveIn: input.moveIn ?? null, message: input.message ?? null });
    for (const a of admins) await sendEmail(a.email, mail.subject, mail.text, mail.html).catch(() => undefined);
  });
  return { id: enquiry.id, createdAt: enquiry.createdAt };
}

// ── Office ──────────────────────────────────────────────────────────────────

const enquiryInclude = { property: { select: { id: true, name: true } } } as const;

async function withBed<T extends { reservedBedId: string | null }>(rows: T[]) {
  const ids = rows.map((r) => r.reservedBedId).filter((x): x is string => !!x);
  const beds = ids.length ? await db.bed.findMany({ where: { id: { in: ids } }, select: { id: true, label: true, status: true, room: { select: { number: true } } } }) : [];
  const byId = new Map(beds.map((b) => [b.id, { id: b.id, label: b.label, status: b.status, room: b.room.number }]));
  return rows.map((r) => ({ ...r, reservedBed: r.reservedBedId ? (byId.get(r.reservedBedId) ?? null) : null }));
}

export async function listEnquiries(filters: { status?: EnquiryStatus; propertyId?: string; q?: string }, pagination?: Pagination | null) {
  const where = {
    ...(filters.status ? { status: filters.status } : {}),
    ...(filters.propertyId ? { propertyId: filters.propertyId } : {}),
    ...(filters.q ? { OR: [{ name: { contains: filters.q, mode: 'insensitive' as const } }, { phone: { contains: filters.q } }] } : {}),
  };
  const orderBy = { createdAt: 'desc' as const };
  if (!pagination) return withBed(await db.enquiry.findMany({ where, include: enquiryInclude, orderBy, take: 300 }));
  const [items, total] = await Promise.all([
    db.enquiry.findMany({ where, include: enquiryInclude, orderBy, skip: pagination.skip, take: pagination.limit }),
    db.enquiry.count({ where }),
  ]);
  return paginated(await withBed(items), total, pagination);
}

export async function enquirySummary(propertyId?: string) {
  const where = propertyId ? { propertyId } : {};
  const rows = await db.enquiry.groupBy({ by: ['status'], where, _count: { _all: true } });
  const by = (s: EnquiryStatus) => rows.find((r) => r.status === s)?._count._all ?? 0;
  return { new: by(EnquiryStatus.NEW), contacted: by(EnquiryStatus.CONTACTED), reserved: by(EnquiryStatus.RESERVED), converted: by(EnquiryStatus.CONVERTED), closed: by(EnquiryStatus.CLOSED) };
}

export async function updateEnquiry(id: string, input: { status?: EnquiryStatus; note?: string | null }) {
  const existing = await db.enquiry.findFirst({ where: { id } });
  if (!existing) throw new NotFoundError('Enquiry not found');
  if (input.status === EnquiryStatus.RESERVED) throw new BadRequestError('Reserve a bed to move an enquiry to Reserved');
  // Leaving RESERVED by hand frees the bed, so a status change never strands one.
  const leavingHold = existing.status === EnquiryStatus.RESERVED && !!input.status;
  if (leavingHold) await freeBed(existing.reservedBedId);
  const updated = await db.enquiry.update({
    where: { id },
    data: {
      ...(input.status ? { status: input.status } : {}),
      ...(input.note !== undefined ? { note: input.note } : {}),
      ...(leavingHold ? { reservedBedId: null, reservedUntil: null } : {}),
    },
    include: enquiryInclude,
  });
  return (await withBed([updated]))[0];
}

async function freeBed(bedId: string | null) {
  if (!bedId) return;
  const bed = await db.bed.findFirst({ where: { id: bedId }, select: { status: true, student: { select: { id: true } } } });
  if (bed && bed.status === BedStatus.RESERVED && !bed.student) await db.bed.update({ where: { id: bedId }, data: { status: BedStatus.VACANT } });
}

/** Hold a vacant bed in the enquiry's property for a few days. */
export async function reserveBed(id: string, bedId: string, days: number) {
  const enquiry = await db.enquiry.findFirst({ where: { id } });
  if (!enquiry) throw new NotFoundError('Enquiry not found');
  if (enquiry.status === EnquiryStatus.CONVERTED || enquiry.status === EnquiryStatus.CLOSED) throw new ConflictError('This enquiry is closed');
  const bed = await db.bed.findFirst({ where: { id: bedId, archivedAt: null }, include: { room: { select: { propertyId: true, number: true } }, student: { select: { id: true } } } });
  if (!bed || bed.room.propertyId !== enquiry.propertyId) throw new NotFoundError('That bed is not in this property');
  if (bed.status !== BedStatus.VACANT || bed.student) throw new ConflictError(`Bed ${bed.label} in room ${bed.room.number} is not free`);
  // Swapping beds releases the earlier hold.
  if (enquiry.reservedBedId && enquiry.reservedBedId !== bedId) await freeBed(enquiry.reservedBedId);
  await db.bed.update({ where: { id: bedId }, data: { status: BedStatus.RESERVED } });
  const updated = await db.enquiry.update({
    where: { id },
    data: { status: EnquiryStatus.RESERVED, reservedBedId: bedId, reservedUntil: new Date(Date.now() + days * 86_400_000) },
    include: enquiryInclude,
  });
  return (await withBed([updated]))[0];
}

/** Let the bed go; the enquiry goes back to Contacted. */
export async function releaseReservation(id: string) {
  const enquiry = await db.enquiry.findFirst({ where: { id } });
  if (!enquiry) throw new NotFoundError('Enquiry not found');
  if (enquiry.status !== EnquiryStatus.RESERVED) throw new ConflictError('No bed is held for this enquiry');
  await freeBed(enquiry.reservedBedId);
  const updated = await db.enquiry.update({ where: { id }, data: { status: EnquiryStatus.CONTACTED, reservedBedId: null, reservedUntil: null }, include: enquiryInclude });
  return (await withBed([updated]))[0];
}

/**
 * Hourly: holds past their date are released so a bed is never kept for
 * someone who did not come. Unscoped — no request context on the tick.
 */
export async function releaseExpiredReservations(now = new Date()): Promise<{ released: number }> {
  const due = await prismaUnscoped.enquiry.findMany({ where: { status: EnquiryStatus.RESERVED, reservedUntil: { lt: now } }, take: 200 });
  for (const e of due) {
    if (e.reservedBedId) {
      const bed = await prismaUnscoped.bed.findFirst({ where: { id: e.reservedBedId }, select: { status: true, student: { select: { id: true } } } });
      if (bed && bed.status === BedStatus.RESERVED && !bed.student) await prismaUnscoped.bed.update({ where: { id: e.reservedBedId }, data: { status: BedStatus.VACANT } });
    }
    await prismaUnscoped.enquiry.update({
      where: { id: e.id },
      data: { status: EnquiryStatus.CONTACTED, reservedBedId: null, reservedUntil: null, note: [e.note, `Hold expired ${now.toISOString().slice(0, 10)}`].filter(Boolean).join(' · ') },
    });
  }
  return { released: due.length };
}

/** Beds the office can hold for an enquiry: the free ones in its property. */
export async function freeBedsFor(enquiryId: string) {
  const enquiry = await db.enquiry.findFirst({ where: { id: enquiryId }, select: { propertyId: true } });
  if (!enquiry) throw new NotFoundError('Enquiry not found');
  const beds = await db.bed.findMany({
    where: { status: BedStatus.VACANT, archivedAt: null, room: { propertyId: enquiry.propertyId } },
    select: { id: true, label: true, monthlyRent: true, room: { select: { number: true, type: true, floor: true, monthlyRent: true } } },
    orderBy: [{ room: { number: 'asc' } }, { label: 'asc' }],
  });
  return beds.map((b) => ({ id: b.id, label: b.label, room: b.room.number, type: b.room.type, floor: b.room.floor, rent: b.monthlyRent ?? b.room.monthlyRent }));
}

export function tenantIdOrThrow() {
  return getTenantIdOrThrow();
}
