import { Role, TenantKind, TenantPlan, TenantStatus } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';
import { hashPassword } from '../../lib/password';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { toPublicUser } from '../auth/auth.service';
import type { CreateTenantInput } from './tenant.schemas';
import { planShortfall, tenantUsage } from '../plans/plan-limits';
import { accessSummary, assertCanActivate, initialAccess } from './tenant-access.service';
import { createInvoice } from '../subscriptions/subscriptions.service';

/** Refuse a plan the tenant has already outgrown. */
async function assertPlanFits(tenantId: string, plan: { name: string; maxProperties: number | null; maxBeds: number | null }) {
  const why = planShortfall(plan, await tenantUsage(tenantId));
  if (why) throw new ConflictError(`The ${plan.name} plan is too small: this tenant already has ${why}. Pick a bigger plan.`, 'PLAN_BELOW_USAGE');
}

const planSelect = {
  select: { id: true, name: true, monthlyPrice: true, maxProperties: true, maxRooms: true, maxStudents: true, maxBeds: true },
} as const;

/**
 * SUPER_ADMIN operation — cross-tenant, so it uses the UNSCOPED client.
 * Creates the Tenant and its first HOSTEL_ADMIN atomically.
 *
 * The self-serve free trial (Sprint L2) calls it too, with no creator and a
 * password that was hashed when the owner filled in the form.
 */
export async function createTenantWithAdmin(input: CreateTenantInput, createdById: string | null, opts: { passwordHash?: string } = {}) {
  const emailTaken = await prismaUnscoped.user.findUnique({ where: { email: input.hostelAdmin.email } });
  if (emailTaken) throw new ConflictError('Hostel Admin email already registered');

  // A paid plan chosen as the access wins; then an explicit plan; otherwise
  // whichever plan is marked default.
  let planId = input.access?.kind === 'PLAN' ? input.access.planId : input.planId ?? null;
  if (planId) {
    const plan = await prismaUnscoped.plan.findUnique({ where: { id: planId } });
    if (!plan) throw new NotFoundError('Plan not found');
  } else {
    planId = (await prismaUnscoped.plan.findFirst({ where: { isDefault: true } }))?.id ?? null;
  }

  const passwordHash = opts.passwordHash ?? (await hashPassword(input.hostelAdmin.password));

  const result = await prismaUnscoped.$transaction(async (tx) => {
    const tenant = await tx.tenant.create({
      data: { name: input.name, kind: input.kind ?? TenantKind.HOSTEL, plan: input.plan ?? TenantPlan.FREE, planId, ...initialAccess(input.access) },
    });
    const admin = await tx.user.create({
      data: {
        tenantId: tenant.id,
        role: Role.HOSTEL_ADMIN,
        name: input.hostelAdmin.name,
        email: input.hostelAdmin.email,
        phone: input.hostelAdmin.phone,
        passwordHash,
        createdById,
      },
    });

    // Every tenant gets a first property here rather than lazily on first
    // read, so the details captured at signup are not lost and the hostel
    // admin lands on a configured account instead of an empty one.
    const { name: propertyName, ...details } = input.property ?? {};
    const property = await tx.property.create({
      data: {
        tenantId: tenant.id,
        name: propertyName || `${input.name} — Main`,
        ...details,
        // `city` has a non-null default in the schema; don't overwrite it with
        // undefined when the form left it blank.
        ...(details.city ? { city: details.city } : {}),
      },
    });
    return { tenant, admin, property };
  });

  // A paid plan's first invoice, as a draft to review and send, unless declined.
  let invoice: { id: string; invoiceNumber: string | null; amount: number } | null = null;
  const access = input.access;
  if (access?.kind === 'PLAN' && access.raiseInvoice !== false && createdById) {
    const t = result.tenant;
    const plan = await prismaUnscoped.plan.findUnique({ where: { id: access.planId } });
    if (plan && plan.monthlyPrice > 0) {
      const inv = await createInvoice({ tenantId: t.id, invoiceType: access.cycle, issueDate: t.accessStartsOn!, periodStart: t.accessStartsOn, periodEnd: t.accessEndsOn, note: `${plan.name} plan` }, createdById);
      invoice = { id: inv.id, invoiceNumber: inv.invoiceNumber, amount: inv.amount };
    }
  }

  return { tenant: { ...result.tenant, access: accessSummary(result.tenant) }, hostelAdmin: toPublicUser(result.admin), property: result.property, invoice };
}

export async function listTenants() {
  const tenants = await prismaUnscoped.tenant.findMany({
    orderBy: { createdAt: 'desc' },
    include: {
      planRef: planSelect,
      _count: { select: { users: true, properties: true, studentProfiles: true, rooms: true, beds: true } },
    },
  });
  return tenants.map((t) => ({
    id: t.id,
    name: t.name,
    kind: t.kind,
    status: t.status,
    suspendedAt: t.suspendedAt,
    suspendedReason: t.suspendedReason,
    plan: t.planRef, // null until a plan is assigned
    access: accessSummary(t),
    createdAt: t.createdAt,
    userCount: t._count.users,
    propertyCount: t._count.properties,
    roomCount: t._count.rooms,
    bedCount: t._count.beds,
    studentCount: t._count.studentProfiles,
  }));
}

/** Assign (or clear, with null) a subscription plan for a tenant. */
export async function setTenantPlan(tenantId: string, planId: string | null) {
  const tenant = await prismaUnscoped.tenant.findUnique({ where: { id: tenantId } });
  if (!tenant) throw new NotFoundError('Tenant not found');
  if (planId) {
    const plan = await prismaUnscoped.plan.findUnique({ where: { id: planId } });
    if (!plan) throw new NotFoundError('Plan not found');
    await assertPlanFits(tenantId, plan);
  }
  const updated = await prismaUnscoped.tenant.update({
    where: { id: tenantId },
    data: { planId },
    include: { planRef: planSelect },
  });
  return { id: updated.id, name: updated.name, plan: updated.planRef };
}

/** Full detail for one tenant: usage, admins, and its billing position. */
export async function getTenant(tenantId: string) {
  const tenant = await prismaUnscoped.tenant.findUnique({
    where: { id: tenantId },
    include: {
      planRef: planSelect,
      _count: { select: { users: true, properties: true, studentProfiles: true, rooms: true, beds: true } },
      users: {
        where: { role: Role.HOSTEL_ADMIN },
        select: { id: true, name: true, email: true, phone: true, createdAt: true },
        orderBy: { createdAt: 'asc' },
      },
      subscriptionInvoices: {
        // Drafts are not issued and cancelled invoices are not owed.
        where: { status: { notIn: ['DRAFT', 'VOID'] } },
        select: { id: true, invoiceNumber: true, periodMonth: true, amount: true, status: true, dueDate: true, payments: { select: { amount: true } } },
        orderBy: [{ issueDate: 'desc' }, { periodMonth: 'desc' }],
        take: 12,
      },
    },
  });
  if (!tenant) throw new NotFoundError('Tenant not found');

  const billed = tenant.subscriptionInvoices.reduce((n, i) => n + i.amount, 0);
  const collected = tenant.subscriptionInvoices.reduce(
    (n, i) => n + i.payments.reduce((m, p) => m + p.amount, 0),
    0,
  );

  return {
    id: tenant.id,
    name: tenant.name,
    kind: tenant.kind,
    status: tenant.status,
    suspendedAt: tenant.suspendedAt,
    suspendedReason: tenant.suspendedReason,
    plan: tenant.planRef,
    access: accessSummary(tenant),
    createdAt: tenant.createdAt,
    userCount: tenant._count.users,
    propertyCount: tenant._count.properties,
    roomCount: tenant._count.rooms,
    bedCount: tenant._count.beds,
    studentCount: tenant._count.studentProfiles,
    admins: tenant.users,
    billing: { billed, collected, outstanding: Math.max(0, billed - collected) },
  };
}

/** Rename a tenant, and/or move it to a different plan, in one call. */
export async function updateTenant(tenantId: string, input: { name?: string; planId?: string | null; kind?: TenantKind }) {
  const tenant = await prismaUnscoped.tenant.findUnique({ where: { id: tenantId } });
  if (!tenant) throw new NotFoundError('Tenant not found');
  // Enterprise is chosen when the tenant is created. Moving a live hostel in
  // would hide its billing at once; moving one out would strand its records.
  if (input.kind !== undefined && input.kind !== tenant.kind && (input.kind === TenantKind.ENTERPRISE || tenant.kind === TenantKind.ENTERPRISE)) {
    throw new ConflictError('A tenant cannot be changed to or from Enterprise', 'KIND_LOCKED');
  }

  if (input.planId) {
    const plan = await prismaUnscoped.plan.findUnique({ where: { id: input.planId } });
    if (!plan) throw new NotFoundError('Plan not found');
    if (input.planId !== tenant.planId) await assertPlanFits(tenantId, plan);
  }

  const updated = await prismaUnscoped.tenant.update({
    where: { id: tenantId },
    data: {
      ...(input.name !== undefined ? { name: input.name } : {}),
      ...(input.planId !== undefined ? { planId: input.planId } : {}),
      ...(input.kind !== undefined ? { kind: input.kind } : {}),
    },
    include: { planRef: planSelect },
  });
  return { id: updated.id, name: updated.name, kind: updated.kind, status: updated.status, plan: updated.planRef };
}

/**
 * Suspend or restore a hostel account.
 *
 * Suspension is the REVERSIBLE lever for non-payment: it blocks every login
 * for the tenant (see assertTenantActive in auth.service) but destroys
 * nothing. Prefer it to deletion in almost every real case.
 */
export async function setTenantStatus(tenantId: string, status: TenantStatus, reason?: string, now = new Date()) {
  const tenant = await prismaUnscoped.tenant.findUnique({ where: { id: tenantId } });
  if (!tenant) throw new NotFoundError('Tenant not found');
  // Bringing back a hostel whose days have run out needs a renewal, or the
  // clock would suspend it again within the hour.
  if (status === TenantStatus.ACTIVE) await assertCanActivate(tenantId, now);

  const updated = await prismaUnscoped.tenant.update({
    where: { id: tenantId },
    data:
      status === TenantStatus.SUSPENDED
        ? { status, suspendedAt: new Date(), suspendedReason: reason ?? null, suspendedCause: 'MANUAL' }
        : { status, suspendedAt: null, suspendedReason: null, suspendedCause: null },
    include: { planRef: planSelect },
  });
  return {
    id: updated.id,
    name: updated.name,
    status: updated.status,
    suspendedAt: updated.suspendedAt,
    suspendedReason: updated.suspendedReason,
    plan: updated.planRef,
  };
}

/**
 * Permanently delete a tenant and everything it owns.
 *
 * This is irreversible and deliberately hard to trigger by accident:
 *
 *  1. The caller must echo the tenant's exact name as confirmation.
 *  2. A tenant with COLLECTED subscription payments cannot be deleted at
 *     all. Those rows are our own revenue record — erasing them would
 *     falsify the platform's books. Suspend such a tenant instead.
 *
 * Everything else is removed inside one transaction, children first,
 * because the schema models these relations as required with no cascade.
 */
export async function deleteTenant(tenantId: string, confirmName: string) {
  const tenant = await prismaUnscoped.tenant.findUnique({
    where: { id: tenantId },
    include: { _count: { select: { subscriptionPayments: true, studentProfiles: true, users: true } } },
  });
  if (!tenant) throw new NotFoundError('Tenant not found');

  if (confirmName !== tenant.name) {
    throw new BadRequestError('Type the hostel name exactly to confirm deletion');
  }
  if (tenant._count.subscriptionPayments > 0) {
    throw new ConflictError(
      `${tenant.name} has ${tenant._count.subscriptionPayments} recorded subscription payment(s). ` +
        'Deleting it would erase collected revenue from the platform ledger — suspend the account instead.',
    );
  }

  const removed = { ...tenant._count };

  await prismaUnscoped.$transaction(async (tx) => {
    const where = { where: { tenantId } };
    // Children before parents — these relations are required, not cascading.
    // Every tenant-owned table must appear here; a table added elsewhere and
    // forgotten here surfaces as a foreign-key error at the worst moment.
    await tx.accountDeletionRequest.deleteMany(where);
    await tx.reminderLog.deleteMany(where);
    await tx.notificationLog.deleteMany(where);
    await tx.subscriptionInvoice.deleteMany(where);
    await tx.paymentRequest.deleteMany(where);
    await tx.payment.deleteMany(where);
    await tx.hostelPaymentAccount.deleteMany(where);
    await tx.virtualAccount.deleteMany(where);
    await tx.stay.deleteMany(where);
    await tx.gatePunch.deleteMany(where);
    await tx.gatePass.deleteMany(where);
    await tx.visitor.deleteMany(where);
    await tx.guardianLink.deleteMany(where);
    await tx.gatePunch.deleteMany(where);
    await tx.gatePass.deleteMany(where);
    await tx.visitor.deleteMany(where);
    await tx.guardianLink.deleteMany(where);
    await tx.settlement.deleteMany(where);
    await tx.roomAssetCheck.deleteMany(where);
    await tx.moveOut.deleteMany(where);
    await tx.roomAssetTemplate.deleteMany(where);
    await tx.reconciliationRun.deleteMany(where);
    await tx.studentCharge.deleteMany(where);
    await tx.invoiceLine.deleteMany(where);
    await tx.invoice.deleteMany(where);
    await tx.chargeAssignment.deleteMany(where);
    await tx.chargeType.deleteMany(where);
    await tx.biometricPunch.deleteMany(where);
    await tx.biometricDevice.deleteMany(where);
    await tx.attachment.deleteMany(where);
    await tx.inboxItem.deleteMany(where);
    await tx.reportSchedule.deleteMany(where);
    await tx.rosterEntry.deleteMany(where);
    await tx.leaveAllocation.deleteMany(where);
    await tx.departmentApprover.deleteMany(where);
    await tx.disciplineIncident.deleteMany(where);
    await tx.feedback.deleteMany(where);
    await tx.parcel.deleteMany(where);
    await tx.emergencyContact.deleteMany(where);
    await tx.lostFoundItem.deleteMany(where);
    await tx.cleaningTask.deleteMany(where);
    await tx.cleaningArea.deleteMany(where);
    await tx.roomAudit.deleteMany(where);
    await tx.roomAsset.deleteMany(where);
    await tx.workOrder.deleteMany(where);
    await tx.storeMovement.deleteMany(where);
    await tx.storeItem.deleteMany(where);
    await tx.laundryOrder.deleteMany(where);
    await tx.laundryBatch.deleteMany(where);
    await tx.staffPunch.deleteMany(where);
    await tx.staffDuty.deleteMany(where);
    await tx.integrationRun.deleteMany(where);
    await tx.complianceAudit.deleteMany(where);
    await tx.complianceFinding.deleteMany(where);
    await tx.complianceInspection.deleteMany(where);
    await tx.complianceItem.deleteMany(where);
    await tx.assistanceRequest.deleteMany(where);
    await tx.accessibilityProfile.deleteMany(where);
    await tx.medicalAccessLog.deleteMany(where);
    await tx.medicalAppointment.deleteMany(where);
    await tx.ohcVisit.deleteMany(where);
    await tx.medicalRecord.deleteMany(where);
    await tx.mealRating.deleteMany(where);
    await tx.dietMenu.deleteMany(where);
    await tx.dietProfile.deleteMany(where);
    await tx.mealWindow.deleteMany(where);
    await tx.emergencyTeamMember.deleteMany(where);
    await tx.emergencyAck.deleteMany(where);
    await tx.emergencyAlert.deleteMany(where);
    await tx.eventRegistration.deleteMany(where);
    await tx.event.deleteMany(where);
    await tx.energyAlert.deleteMany(where);
    await tx.energySetting.deleteMany(where);
    await tx.busTrip.deleteMany(where);
    await tx.vehicle.deleteMany(where);
    await tx.curfewBreach.deleteMany(where);
    await tx.whatsAppBroadcast.deleteMany(where);
    await tx.noticeAck.deleteMany(where);
    await tx.meterReading.deleteMany(where);
    await tx.energyMeter.deleteMany(where);
    await tx.studentRequestReply.deleteMany(where);
    await tx.studentRequest.deleteMany(where);
    await tx.vendor.deleteMany(where);
    await tx.requestSla.deleteMany(where);
    await tx.enquiry.deleteMany(where);
    await tx.messComplaintReply.deleteMany(where);
    await tx.messComplaint.deleteMany(where);
    await tx.messStockEntry.deleteMany(where);
    await tx.messInventoryItem.deleteMany(where);
    await tx.messSubscription.deleteMany(where);
    await tx.messDay.deleteMany(where);
    await tx.messAttendance.deleteMany(where);
    await tx.messMealOptOut.deleteMany(where);
    await tx.messMenu.deleteMany(where);
    await tx.expense.deleteMany(where);
    await tx.notice.deleteMany(where);
    // A room may point at its billed student; clear that before the profiles go.
    await tx.room.updateMany({ ...where, data: { billedStudentProfileId: null } });
    await tx.studentProfile.deleteMany(where);
    await tx.shift.deleteMany(where);
    await tx.leaveType.deleteMany(where);
    await tx.department.deleteMany(where);
    await tx.bed.deleteMany(where);
    await tx.room.deleteMany(where);
    await tx.tenantSettings.deleteMany(where);
    await tx.property.deleteMany(where);
    // Users reference CustomRole, so clear the link before dropping roles.
    await tx.user.updateMany({ ...where, data: { customRoleId: null } });
    await tx.user.deleteMany(where);
    await tx.customRole.deleteMany(where);
    await tx.tenant.delete({ where: { id: tenantId } });
    // Forty-odd tables, one round trip each: well past the 5-second default
    // on a remote database, and this must finish or roll back whole.
  }, { maxWait: 15_000, timeout: 120_000 });

  return { id: tenantId, name: tenant.name, removed };
}

// ── Account deletion requests ─────────────────────────────────────────────

export async function listDeletionRequests() {
  return prismaUnscoped.accountDeletionRequest.findMany({
    include: { tenant: { select: { id: true, name: true, status: true, _count: { select: { users: true, studentProfiles: true } } } } },
    // Pending first, newest first — the queue is the point.
    orderBy: [{ status: 'asc' }, { createdAt: 'desc' }],
    take: 200,
  });
}

/**
 * Approving IS the deletion. It runs the same guarded cascade as a direct
 * delete — including the "type the hostel name" confirmation, because a
 * request from the tenant does not make the platform side any less final.
 */
export async function approveDeletionRequest(id: string, confirmName: string, resolvedById: string, note?: string) {
  const request = await prismaUnscoped.accountDeletionRequest.findUnique({ where: { id } });
  if (!request) throw new NotFoundError('Request not found');
  if (request.status !== 'PENDING') throw new ConflictError('That request has already been decided');

  const result = await deleteTenant(request.tenantId, confirmName);
  // The tenant row is gone, so the request must not point at it any more —
  // but the decision is kept as the audit trail. Detach and mark it.
  await prismaUnscoped.accountDeletionRequest.deleteMany({ where: { tenantId: request.tenantId } });
  return { ...result, request: { id, status: 'APPROVED', resolvedById, note } };
}

export async function rejectDeletionRequest(id: string, resolvedById: string, note?: string) {
  const request = await prismaUnscoped.accountDeletionRequest.findUnique({ where: { id } });
  if (!request) throw new NotFoundError('Request not found');
  if (request.status !== 'PENDING') throw new ConflictError('That request has already been decided');
  return prismaUnscoped.accountDeletionRequest.update({
    where: { id },
    data: { status: 'REJECTED', resolvedById, resolutionNote: note, resolvedAt: new Date() },
  });
}
