import { MessComplaintStatus, Role } from '@prisma/client';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { BadRequestError, ForbiddenError, NotFoundError } from '../../lib/errors';
import { paginated, type Pagination } from '../../lib/pagination';

/**
 * Mess complaints, with the admin's replies threaded underneath.
 *
 * A student sees only their own; anyone with MANAGE_MESS sees all. The split
 * matters — a complaint about the food is fine to be seen by staff, but not by
 * the rest of the hostel.
 */

const complaintInclude = {
  student: { include: { user: { select: { id: true, name: true } } } },
  replies: {
    include: { author: { select: { id: true, name: true, role: true } } },
    orderBy: { createdAt: 'asc' as const },
  },
} as const;

async function profileForUser(userId: string) {
  const profile = await db.studentProfile.findFirst({ where: { userId } });
  if (!profile) throw new NotFoundError('No student profile for this account');
  return profile;
}

export async function raiseComplaint(
  userId: string,
  input: { category: string; subject: string; body: string },
) {
  const tenantId = getTenantIdOrThrow();
  const profile = await profileForUser(userId);

  // One shouting match at a time. An unbounded queue of open complaints from
  // one account is a denial-of-service on the admin's attention.
  const open = await db.messComplaint.count({
    where: { studentProfileId: profile.id, status: { not: MessComplaintStatus.RESOLVED } },
  });
  if (open >= 5) {
    throw new BadRequestError('You already have 5 open mess complaints. Wait for those to be answered first.');
  }

  return db.messComplaint.create({
    data: { tenantId, studentProfileId: profile.id, ...input },
    include: complaintInclude,
  });
}

export async function listComplaints(
  filters: {
    status?: MessComplaintStatus;
    category?: string;
    mineForUserId?: string;
    q?: string;
  },
  pagination?: Pagination | null,
) {
  const where = {
    // A student sees only their own thread, whatever else is asked for.
    ...(filters.mineForUserId ? { student: { userId: filters.mineForUserId } } : {}),
    ...(filters.status ? { status: filters.status } : {}),
    ...(filters.category ? { category: filters.category } : {}),
    // The subject, what was written, and who wrote it — an admin looking for
    // "that complaint from Riya about the dal" needs all three.
    ...(filters.q
      ? {
          OR: [
            { subject: { contains: filters.q, mode: 'insensitive' as const } },
            { body: { contains: filters.q, mode: 'insensitive' as const } },
            {
              student: {
                is: {
                  ...(filters.mineForUserId ? { userId: filters.mineForUserId } : {}),
                  user: { is: { name: { contains: filters.q, mode: 'insensitive' as const } } },
                },
              },
            },
          ],
        }
      : {}),
  };
  // Open first, then newest — the admin's queue is what this list is for.
  const orderBy = [{ status: 'asc' as const }, { createdAt: 'desc' as const }];

  if (!pagination) {
    return db.messComplaint.findMany({ where, include: complaintInclude, orderBy, take: 200 });
  }

  const [items, total] = await Promise.all([
    db.messComplaint.findMany({
      where,
      include: complaintInclude,
      orderBy,
      skip: pagination.skip,
      take: pagination.limit,
    }),
    db.messComplaint.count({ where }),
  ]);
  return paginated(items, total, pagination);
}

export async function getComplaint(id: string, viewer: { userId: string; role: Role }) {
  const complaint = await db.messComplaint.findFirst({ where: { id }, include: complaintInclude });
  if (!complaint) throw new NotFoundError('Complaint not found');
  if (viewer.role === Role.STUDENT) {
    const profile = await profileForUser(viewer.userId);
    if (complaint.studentProfileId !== profile.id) throw new NotFoundError('Complaint not found');
  }
  return complaint;
}

/**
 * Reply to a complaint. Both sides may post: an admin asking "which meal?" is
 * useless if the student cannot answer in the same thread.
 */
export async function reply(id: string, viewer: { userId: string; role: Role }, body: string) {
  const tenantId = getTenantIdOrThrow();
  const complaint = await db.messComplaint.findFirst({ where: { id } });
  if (!complaint) throw new NotFoundError('Complaint not found');

  if (viewer.role === Role.STUDENT) {
    const profile = await profileForUser(viewer.userId);
    if (complaint.studentProfileId !== profile.id) throw new ForbiddenError('That is not your complaint');
  }

  await db.messComplaintReply.create({ data: { tenantId, complaintId: id, authorId: viewer.userId, body } });

  // A staff reply moves an untouched complaint out of the OPEN queue, so the
  // admin's list reflects what has actually been picked up.
  if (viewer.role !== Role.STUDENT && complaint.status === MessComplaintStatus.OPEN) {
    await db.messComplaint.update({ where: { id }, data: { status: MessComplaintStatus.IN_PROGRESS } });
  }
  return db.messComplaint.findFirst({ where: { id }, include: complaintInclude });
}

export async function setStatus(id: string, status: MessComplaintStatus) {
  const complaint = await db.messComplaint.findFirst({ where: { id } });
  if (!complaint) throw new NotFoundError('Complaint not found');
  return db.messComplaint.update({
    where: { id },
    data: { status, resolvedAt: status === MessComplaintStatus.RESOLVED ? new Date() : null },
    include: complaintInclude,
  });
}

/** Open counts for the badge on the mess admin's nav. */
export async function complaintSummary() {
  const rows = await db.messComplaint.groupBy({ by: ['status'], _count: { _all: true } });
  const by = (s: MessComplaintStatus) => rows.find((r) => r.status === s)?._count._all ?? 0;
  return {
    open: by(MessComplaintStatus.OPEN),
    inProgress: by(MessComplaintStatus.IN_PROGRESS),
    resolved: by(MessComplaintStatus.RESOLVED),
  };
}
