import { Role, TenantKind } from '@prisma/client';
import { db, prismaUnscoped } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { isValidPeriod } from '../../lib/period';
import { BadRequestError } from '../../lib/errors';

/**
 * Staff salary → expense (Sprint 6).
 *
 * A staff member with a monthly salary and a pay day gets one SALARY expense
 * per month, dated on that day, keyed "salary:<userId>:<YYYY-MM>" so the
 * hourly tick and a manual "post now" can never double it. Nothing posts for
 * staff with no salary set, which is every staff member today.
 */

const STAFF_ROLES = [Role.WARDEN, Role.MESS_ADMIN, Role.GUARD, Role.HOSTEL_ADMIN];
const keyFor = (userId: string, period: string) => `salary:${userId}:${period}`;

/** Today's day-of-month in India; pay days are local days, not UTC ones. */
function istToday(now = new Date()) {
  const ist = new Date(now.getTime() + 5.5 * 3_600_000);
  return { period: ist.toISOString().slice(0, 7), day: ist.getUTCDate() };
}

const monthName = (period: string) => new Date(`${period}-01T00:00:00Z`).toLocaleDateString('en-IN', { month: 'long', year: 'numeric', timeZone: 'UTC' });

/** Who would be paid for a month, and whether they already were. */
export async function salaryPreview(period: string) {
  if (!isValidPeriod(period)) throw new BadRequestError('period (YYYY-MM) is required');
  const staff = await db.staffProfile.findMany({
    where: { monthlySalary: { gt: 0 }, user: { role: { in: STAFF_ROLES } } },
    include: { user: { select: { id: true, name: true, role: true } } },
    orderBy: { createdAt: 'asc' },
  });
  const posted = await db.expense.findMany({ where: { salaryKey: { in: staff.map((s) => keyFor(s.userId, period)) } }, select: { salaryKey: true, id: true, date: true, amount: true } });
  const byKey = new Map(posted.map((p) => [p.salaryKey!, p]));
  const rows = staff.map((s) => {
    const p = byKey.get(keyFor(s.userId, period));
    return { userId: s.userId, name: s.user.name, role: s.user.role, monthlySalary: s.monthlySalary!, salaryDay: s.salaryDay, posted: !!p, expenseId: p?.id ?? null, postedOn: p?.date ?? null };
  });
  return { period, rows, total: rows.reduce((n, r) => n + r.monthlySalary, 0), posted: rows.filter((r) => r.posted).reduce((n, r) => n + r.monthlySalary, 0) };
}

/**
 * Post the month's salaries now, for everyone with a salary set — whatever
 * their pay day. The office pressing the button is the decision.
 */
export async function postSalaries(period: string, actorId: string) {
  if (!isValidPeriod(period)) throw new BadRequestError('period (YYYY-MM) is required');
  const tenantId = getTenantIdOrThrow();
  const preview = await salaryPreview(period);
  let created = 0;
  for (const r of preview.rows) {
    if (r.posted) continue;
    const day = Math.min(r.salaryDay ?? 1, 28);
    await db.expense.create({
      data: { tenantId, category: 'SALARY', amount: r.monthlySalary, date: new Date(`${period}-${String(day).padStart(2, '0')}T00:00:00.000Z`), note: `Salary · ${r.name} · ${monthName(period)}`, recordedById: actorId, salaryKey: keyFor(r.userId, period) },
    });
    created++;
  }
  return { created, ...(await salaryPreview(period)) };
}

/**
 * Hourly: for every hostel, post this month's salary for staff whose pay day
 * has arrived (IST). Unscoped — no request context on the tick.
 */
export async function postSalariesEverywhere(now = new Date()): Promise<{ created: number }> {
  const { period, day } = istToday(now);
  const due = await prismaUnscoped.staffProfile.findMany({
    // Enterprise tenants keep no books here: the company pays its own staff.
    where: { monthlySalary: { gt: 0 }, salaryDay: { lte: day }, user: { role: { in: STAFF_ROLES } }, tenant: { kind: { not: TenantKind.ENTERPRISE } } },
    include: { user: { select: { id: true, name: true } } },
    take: 2000,
  });
  let created = 0;
  for (const s of due) {
    const salaryKey = keyFor(s.userId, period);
    const exists = await prismaUnscoped.expense.findUnique({ where: { salaryKey }, select: { id: true } });
    if (exists) continue;
    await prismaUnscoped.expense.create({
      data: { tenantId: s.tenantId, category: 'SALARY', amount: s.monthlySalary!, date: new Date(`${period}-${String(s.salaryDay).padStart(2, '0')}T00:00:00.000Z`), note: `Salary · ${s.user.name} · ${monthName(period)}`, recordedById: 'system:salary', salaryKey },
    }).catch(() => undefined); // a concurrent tick lost the race on the key — fine
    created++;
  }
  return { created };
}
