import { Role, StudentRequestStatus, StudentRequestType } from '@prisma/client';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { inBackground, notifyRequestAssigned, notifyRequestClosed, notifyRequestCreated, notifyRequestUpdated } from '../notifications/notifications.service';
import { checkCategory } from './grievance.service';
import { effectivePermissions } from '../../lib/permissions';
import { tenantHasFeature } from '../../middleware/requireFeature';
import { BadRequestError, ConflictError, ForbiddenError, NotFoundError } from '../../lib/errors';
import { paginated, type Pagination } from '../../lib/pagination';

/**
 * Student requests — a repair, a room change, leave, a complaint — with the
 * warden's replies threaded underneath.
 *
 * A student sees only their own. Staff with MANAGE_STUDENTS see the queue:
 * the same people who onboard and move students are the ones who answer
 * "my fan is broken". Mess complaints live next door because they go to a
 * different desk.
 */

const OPEN_STATES: StudentRequestStatus[] = [StudentRequestStatus.OPEN, StudentRequestStatus.IN_PROGRESS];

const requestInclude = {
  student: {
    include: {
      user: { select: { id: true, name: true, email: true, phone: true } },
      bed: { include: { room: { select: { number: true, floor: true } } } },
    },
  },
  replies: {
    include: { author: { select: { id: true, name: true, role: true } } },
    orderBy: { createdAt: 'asc' as const },
  },
  // Sprint 6: who was sent. Old clients ignore the extra key.
  vendor: { select: { id: true, name: true, trade: true, phone: true } },
  // Sprint 0 (TEPL): the member of staff it is handed to.
  assignee: { select: { id: true, name: true } },
} as const;

type RequestRow = NonNullable<Awaited<ReturnType<typeof loadRow>>>;
const loadRow = (id: string) => db.studentRequest.findFirst({ where: { id }, include: requestInclude });

/**
 * What staff are shown of an anonymous request (Sprint 0, TEPL): no name, no
 * room, no contact, and the employee's own replies unsigned. The link stays
 * in the database only so the employee can follow their own thread.
 */
export function forStaff<T extends RequestRow | null>(r: T): T {
  if (!r || !r.anonymous) return r;
  const studentUserId = r.student.userId;
  return {
    ...r,
    studentProfileId: '',
    student: {
      id: '',
      userId: '',
      propertyId: r.student.propertyId,
      user: { id: '', name: 'Anonymous', email: '', phone: null },
      bed: null,
    },
    replies: r.replies.map((rep) => (rep.authorId === studentUserId ? { ...rep, authorId: '', author: { id: '', name: 'Anonymous', role: rep.author.role } } : rep)),
  } as unknown as T;
}

export function forStaffList<T extends RequestRow>(rows: T[]): T[] {
  return rows.map((r) => forStaff(r));
}

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;
}

const toDate = (v: string) => new Date(`${v}T00:00:00.000Z`);

export async function createRequest(
  userId: string,
  input: { type: StudentRequestType; subject: string; body: string; fromDate?: string; toDate?: string; anonymous?: boolean; category?: string },
) {
  const tenantId = getTenantIdOrThrow();
  const profile = await profileForUser(userId);

  // Sprint 0 (TEPL): only a complaint can be anonymous, and only where the module is on.
  const anonymous = !!input.anonymous;
  if (anonymous) {
    if (input.type !== StudentRequestType.COMPLAINT) throw new BadRequestError('Only a complaint can be raised anonymously');
    if (!(await tenantHasFeature(tenantId, 'anonymousRequests'))) throw new BadRequestError('Anonymous complaints are not available here');
  }

  let fromDate: Date | undefined;
  let toDate_: Date | undefined;
  if (input.type === StudentRequestType.LEAVE) {
    if (!input.fromDate || !input.toDate) throw new BadRequestError('Leave needs a from and a to date');
    fromDate = toDate(input.fromDate);
    toDate_ = toDate(input.toDate);
    if (toDate_ < fromDate) throw new BadRequestError('Leave cannot end before it starts');
  }

  // A bounded queue per student. Five things unanswered at once is already a
  // conversation to have in person.
  const open = await db.studentRequest.count({
    where: { studentProfileId: profile.id, status: { in: OPEN_STATES } },
  });
  if (open >= 5) {
    throw new BadRequestError('You already have 5 open requests. Wait for those to be answered first.');
  }

  // Sprint 2 (TEPL): a sub-category, from the type's list.
  const category = await checkCategory(input.type, input.category);

  // Sprint 6: a target close time when the hostel has set one for this type.
  const sla = await db.requestSla.findFirst({ where: { type: input.type } });
  // Sprint 6 (TEPL): someone with an accessibility profile comes first — half the time limit.
  const special = (await tenantHasFeature(tenantId, 'specialNeeds')) && !!(await db.accessibilityProfile.findFirst({ where: { studentProfileId: profile.id }, select: { id: true } }));
  const dueBy = sla ? new Date(Date.now() + (special ? sla.hours / 2 : sla.hours) * 3_600_000) : undefined;

  const created = await db.studentRequest.create({
    data: {
      tenantId,
      studentProfileId: profile.id,
      type: input.type,
      subject: input.subject,
      body: input.body,
      fromDate,
      toDate: toDate_,
      dueBy,
      anonymous,
      ...(category ? { category } : {}),
      ...(special ? { priority: 'SPECIAL_NEEDS' } : {}),
    },
    include: requestInclude,
  });
  inBackground('push: new request', () => notifyRequestCreated(tenantId, created.id));
  return created;
}

export async function listRequests(
  filters: {
    status?: StudentRequestStatus;
    type?: StudentRequestType;
    q?: string;
    mineForUserId?: string;
    /** ACTIVE is the queue's default: everything not yet closed. */
    openOnly?: boolean;
    closedOnly?: boolean;
    /** Sprint 6: still open and past the SLA target. */
    breachedOnly?: boolean;
    /** Sprint 0 (TEPL): a user id, or 'none' for nobody yet. */
    assigneeId?: string;
    /** Sprint 2 (TEPL): a grievance sub-category. */
    category?: string;
    /** Sprint 2 (TEPL): escalated for running past the target. */
    escalatedOnly?: boolean;
  },
  pagination?: Pagination | null,
) {
  const where = {
    // A student's own thread is scoped by the account, never by a query the
    // client sends. The filters below narrow within that, never past it.
    ...(filters.mineForUserId ? { student: { userId: filters.mineForUserId } } : {}),
    ...(filters.status ? { status: filters.status } : {}),
    ...(filters.type ? { type: filters.type } : {}),
    // Active and closed are asked of the database rather than of the page:
    // the queue's default view would otherwise hide most of what matches.
    ...(filters.openOnly ? { status: { in: OPEN_STATES } } : {}),
    ...(filters.closedOnly ? { status: { notIn: OPEN_STATES } } : {}),
    ...(filters.breachedOnly ? { status: { in: OPEN_STATES }, dueBy: { lt: new Date() } } : {}),
    ...(filters.assigneeId ? { assigneeId: filters.assigneeId === 'none' ? null : filters.assigneeId } : {}),
    ...(filters.category ? { category: filters.category } : {}),
    ...(filters.escalatedOnly ? { escalationLevel: { gt: 0 }, status: { in: OPEN_STATES } } : {}),
    ...(filters.q
      ? {
          OR: [
            { subject: { contains: filters.q, mode: 'insensitive' as const } },
            {
              // Staff can never find an anonymous request by who raised it.
              ...(filters.mineForUserId ? {} : { anonymous: false }),
              student: {
                is: {
                  ...(filters.mineForUserId ? { userId: filters.mineForUserId } : {}),
                  user: { is: { name: { contains: filters.q, mode: 'insensitive' as const } } },
                },
              },
            },
            // The room a request came from — what a warden actually
            // remembers about "the broken fan on the second floor".
            {
              ...(filters.mineForUserId ? {} : { anonymous: false }),
              student: {
                is: {
                  ...(filters.mineForUserId ? { userId: filters.mineForUserId } : {}),
                  bed: { is: { room: { is: { number: { contains: filters.q, mode: 'insensitive' as const } } } } },
                },
              },
            },
          ],
        }
      : {}),
  };
  // Open first, then newest — this list is a queue for staff and a
  // "what's still pending" for the student.
  const orderBy = [{ status: 'asc' as const }, { createdAt: 'desc' as const }];

  if (!pagination) {
    return db.studentRequest.findMany({ where, include: requestInclude, orderBy, take: 300 });
  }

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

async function loadForViewer(id: string, viewer: { userId: string; role: Role; perms?: string[] }) {
  const request = await db.studentRequest.findFirst({ where: { id }, include: requestInclude });
  if (!request) throw new NotFoundError('Request not found');
  if (viewer.role === Role.STUDENT) {
    const profile = await profileForUser(viewer.userId);
    // Not found rather than forbidden: no hint that another id exists.
    if (request.studentProfileId !== profile.id) throw new NotFoundError('Request not found');
  } else if (viewer.perms && !viewer.perms.includes('MANAGE_STUDENTS') && request.assigneeId !== viewer.userId) {
    // Staff who do not run the queue see only what is handed to them —
    // refused as before Sprint 0, so older clients see no change.
    throw new ForbiddenError('You do not have permission to handle student requests');
  }
  return request;
}

/**
 * Staff may handle a request when they run the queue (MANAGE_STUDENTS) or it
 * is handed to them. Students are checked by ownership in loadForViewer.
 */
export async function assertCanHandle(id: string, viewer: { userId: string; perms: string[] }) {
  if (viewer.perms.includes('MANAGE_STUDENTS')) return;
  const r = await db.studentRequest.findFirst({ where: { id }, select: { assigneeId: true } });
  if (!r || r.assigneeId !== viewer.userId) throw new ForbiddenError('You do not have permission to handle student requests');
}

export const getRequest = loadForViewer;

/** Both sides may reply — a warden asking "which switch?" needs an answer in the thread. */
export async function reply(id: string, viewer: { userId: string; role: Role; perms?: string[] }, body: string) {
  const tenantId = getTenantIdOrThrow();
  const request = await loadForViewer(id, viewer);
  if (request.status === StudentRequestStatus.CANCELLED) {
    throw new ConflictError('This request was withdrawn');
  }

  const created = await db.studentRequestReply.create({ data: { tenantId, requestId: id, authorId: viewer.userId, body } });

  // A staff reply is the pick-up: the queue should show it is being handled.
  if (viewer.role !== Role.STUDENT && request.status === StudentRequestStatus.OPEN) {
    await db.studentRequest.update({ where: { id }, data: { status: StudentRequestStatus.IN_PROGRESS } });
  }
  // The office answered: tell the student.
  if (viewer.role !== Role.STUDENT) {
    inBackground('push: request reply', () => notifyRequestUpdated(tenantId, id, { replyId: created.id }));
  }
  return db.studentRequest.findFirst({ where: { id }, include: requestInclude });
}

const CLOSED: StudentRequestStatus[] = [
  StudentRequestStatus.APPROVED,
  StudentRequestStatus.REJECTED,
  StudentRequestStatus.RESOLVED,
  StudentRequestStatus.CANCELLED,
];

/** Staff decision. Reopening is allowed — a "fixed" fan that isn't is common. */
export async function setStatus(id: string, status: StudentRequestStatus, actorId?: string) {
  if (status === StudentRequestStatus.CANCELLED) {
    throw new BadRequestError('Only the student can withdraw a request');
  }
  const request = await db.studentRequest.findFirst({ where: { id } });
  if (!request) throw new NotFoundError('Request not found');
  if (request.status === StudentRequestStatus.CANCELLED) {
    throw new ConflictError('This request was withdrawn by the student');
  }
  await db.studentRequest.update({
    where: { id },
    data: { status, resolvedAt: CLOSED.includes(status) ? new Date() : null },
  });
  if (status !== request.status) {
    const tenantId = getTenantIdOrThrow();
    inBackground('push: request status', () => notifyRequestUpdated(tenantId, id, { status }));
    // Sprint 2 (TEPL): closing a complaint or repair also tells them by email and WhatsApp.
    if ((status === StudentRequestStatus.RESOLVED || status === StudentRequestStatus.REJECTED) && (await tenantHasFeature(tenantId, 'grievanceDesk'))) {
      inBackground('alert: request closed', () => notifyRequestClosed(tenantId, id));
    }
  }
  // Closing a request with a cost on it books the cost (Sprint 6).
  if (CLOSED.includes(status) && actorId) await postRequestCost(id, actorId);
  return db.studentRequest.findFirst({ where: { id }, include: requestInclude });
}

/** The student withdrawing — only while nobody has picked it up. */
export async function cancelRequest(id: string, userId: string) {
  const request = await loadForViewer(id, { userId, role: Role.STUDENT });
  if (request.status !== StudentRequestStatus.OPEN) {
    throw new ConflictError('Only a request nobody has picked up yet can be withdrawn');
  }
  return db.studentRequest.update({
    where: { id },
    data: { status: StudentRequestStatus.CANCELLED, resolvedAt: new Date() },
    include: requestInclude,
  });
}

/** Counts for the KPI strip and the nav badge. */
export async function requestSummary(mineForUserId?: string) {
  const where = mineForUserId ? { student: { userId: mineForUserId } } : {};
  const rows = await db.studentRequest.groupBy({ by: ['status'], where, _count: { _all: true } });
  const by = (s: StudentRequestStatus) => rows.find((r) => r.status === s)?._count._all ?? 0;
  // Sprint 6: open past the SLA target. Zero for a hostel with no SLAs set.
  const breached = await db.studentRequest.count({ where: { ...where, status: { in: OPEN_STATES }, dueBy: { lt: new Date() } } });
  return {
    open: by(StudentRequestStatus.OPEN),
    inProgress: by(StudentRequestStatus.IN_PROGRESS),
    approved: by(StudentRequestStatus.APPROVED),
    rejected: by(StudentRequestStatus.REJECTED),
    resolved: by(StudentRequestStatus.RESOLVED),
    cancelled: by(StudentRequestStatus.CANCELLED),
    breached,
  };
}

export function assertCanManage(perms: string[] | undefined) {
  if (!perms?.includes('MANAGE_STUDENTS')) {
    throw new ForbiddenError('You do not have permission to handle student requests');
  }
}

// ── SLAs, vendors and costs (Sprint 6) ──────────────────────────────────────

/** Target hours per request type. Types without a row have no target. */
export function listSlas() {
  return db.requestSla.findMany({ orderBy: { type: 'asc' } });
}

/** Replace the whole set. `hours: 0` or a missing type removes the target. */
export async function setSlas(items: { type: StudentRequestType; hours: number }[]) {
  const tenantId = getTenantIdOrThrow();
  const keep = items.filter((i) => i.hours > 0);
  await db.requestSla.deleteMany({ where: { type: { notIn: keep.map((k) => k.type) } } });
  for (const k of keep) {
    const existing = await db.requestSla.findFirst({ where: { type: k.type } });
    if (existing) await db.requestSla.update({ where: { id: existing.id }, data: { hours: k.hours } });
    else await db.requestSla.create({ data: { tenantId, type: k.type, hours: k.hours } });
  }
  return listSlas();
}

export function listVendors(includeArchived = false) {
  return db.vendor.findMany({ where: includeArchived ? {} : { isArchived: false }, orderBy: [{ isArchived: 'asc' }, { name: 'asc' }] });
}

export async function createVendor(input: { name: string; trade?: string; phone?: string; note?: string }, propertyId?: string) {
  const tenantId = getTenantIdOrThrow();
  return db.vendor.create({ data: { tenantId, propertyId, ...input } });
}

export async function updateVendor(id: string, input: { name?: string; trade?: string | null; phone?: string | null; note?: string | null; isArchived?: boolean }) {
  const existing = await db.vendor.findFirst({ where: { id } });
  if (!existing) throw new NotFoundError('Vendor not found');
  return db.vendor.update({ where: { id }, data: input });
}

/**
 * Staff bookkeeping on a request: who is sent, when it is due, what it cost.
 * A cost on an already-closed request posts straight away; on an open one it
 * waits for the close.
 */
export async function patchRequest(id: string, input: { vendorId?: string | null; dueBy?: Date | null; cost?: number | null }, actorId: string) {
  const request = await db.studentRequest.findFirst({ where: { id } });
  if (!request) throw new NotFoundError('Request not found');
  if (input.vendorId) {
    const vendor = await db.vendor.findFirst({ where: { id: input.vendorId } });
    if (!vendor) throw new NotFoundError('Vendor not found');
  }
  // Where the operator keeps no books (Enterprise), a request carries no cost.
  if (input.cost !== undefined && !(await tenantHasFeature(getTenantIdOrThrow(), 'expenses'))) input = { ...input, cost: undefined };
  if (input.cost !== undefined && request.costExpenseId) {
    throw new ConflictError('The cost is already booked as an expense — change it under Expenses');
  }
  await db.studentRequest.update({
    where: { id },
    data: {
      ...(input.vendorId !== undefined ? { vendorId: input.vendorId } : {}),
      ...(input.dueBy !== undefined ? { dueBy: input.dueBy } : {}),
      ...(input.cost !== undefined ? { cost: input.cost } : {}),
    },
  });
  if (CLOSED.includes(request.status)) await postRequestCost(id, actorId);
  return db.studentRequest.findFirst({ where: { id }, include: requestInclude });
}

/** Book the request's cost as an expense, once. No cost, or already booked: no-op. */
async function postRequestCost(id: string, actorId: string) {
  const request = await db.studentRequest.findFirst({ where: { id }, include: { vendor: { select: { name: true } }, student: { select: { propertyId: true } } } });
  if (!request || !request.cost || request.cost <= 0 || request.costExpenseId) return;
  const tenantId = getTenantIdOrThrow();
  if (!(await tenantHasFeature(tenantId, 'expenses'))) return;
  const expense = await db.expense.create({
    data: {
      tenantId,
      propertyId: request.student.propertyId ?? undefined,
      category: request.type === StudentRequestType.MAINTENANCE ? 'MAINTENANCE' : 'OTHER',
      amount: request.cost,
      date: new Date(),
      note: `Request: ${request.subject}${request.vendor ? ` · ${request.vendor.name}` : ''}`,
      recordedById: actorId,
    },
  });
  await db.studentRequest.update({ where: { id }, data: { costExpenseId: expense.id } });
}

// ── Assignment (Sprint 0, TEPL) ─────────────────────────────────────────────

const STAFF_ROLES: Role[] = [Role.HOSTEL_ADMIN, Role.WARDEN, Role.MESS_ADMIN];

/** Staff a request can be handed to: anyone who works tasks or runs the queue. */
export async function assignableStaff() {
  const users = await db.user.findMany({
    where: { role: { in: STAFF_ROLES }, deactivatedAt: null, hasLogin: true },
    select: { id: true, name: true, role: true, customRole: { select: { name: true, permissions: true } } },
    orderBy: { name: 'asc' },
    take: 500,
  });
  return users
    .filter((u) => {
      const perms = effectivePermissions(u.role, u.customRole?.permissions);
      return perms.includes('WORK_TASKS') || perms.includes('MANAGE_STUDENTS');
    })
    .map((u) => ({ id: u.id, name: u.name, role: u.role, roleName: u.customRole?.name ?? null }));
}

/** Hand a request to a member of staff, or take it back (null). Handing it over picks it up. */
export async function assignRequest(id: string, assigneeId: string | null, actorId: string) {
  const request = await db.studentRequest.findFirst({ where: { id } });
  if (!request) throw new NotFoundError('Request not found');
  if (!OPEN_STATES.includes(request.status)) throw new ConflictError('This request is closed — reopen it before handing it over');
  if (assigneeId) {
    const staff = await assignableStaff();
    if (!staff.some((u) => u.id === assigneeId)) throw new BadRequestError('Choose a member of staff who works tasks');
  }
  await db.studentRequest.update({
    where: { id },
    data: {
      assigneeId,
      assignedAt: assigneeId ? new Date() : null,
      ...(assigneeId && request.status === StudentRequestStatus.OPEN ? { status: StudentRequestStatus.IN_PROGRESS } : {}),
    },
  });
  if (assigneeId && assigneeId !== request.assigneeId && assigneeId !== actorId) {
    const tenantId = getTenantIdOrThrow();
    inBackground('push: request assigned', () => notifyRequestAssigned(tenantId, id, assigneeId));
  }
  return loadRow(id);
}

/**
 * The same task list a page at a time (Sprint L3), in the same order; the id
 * breaks ties. `overdue` (Sprint L4) counts every open task past its due time,
 * on any page, so the card no longer counts only the rows loaded.
 */
export async function pageAssigned(userId: string, openOnly: boolean, pagination: Pagination, now = new Date()) {
  const where = { assigneeId: userId, ...(openOnly ? { status: { in: OPEN_STATES } } : {}) };
  const [items, total, overdue] = await Promise.all([
    db.studentRequest.findMany({ where, include: requestInclude, orderBy: [{ status: 'asc' }, { dueBy: 'asc' }, { createdAt: 'desc' }, { id: 'asc' }], skip: pagination.skip, take: pagination.limit }),
    db.studentRequest.count({ where }),
    db.studentRequest.count({ where: { assigneeId: userId, status: { in: OPEN_STATES }, dueBy: { lt: now } } }),
  ]);
  return { ...paginated(items, total, pagination), overdue };
}

/** What is handed to this member of staff: open first, then the latest closed. */
export async function listAssigned(userId: string, openOnly: boolean) {
  return db.studentRequest.findMany({
    where: { assigneeId: userId, ...(openOnly ? { status: { in: OPEN_STATES } } : {}) },
    include: requestInclude,
    orderBy: [{ status: 'asc' }, { dueBy: 'asc' }, { createdAt: 'desc' }],
    take: 200,
  });
}
