import type { z } from 'zod'

import { prisma } from '@/lib/db'
import { AUDIT_ACTIONS, writeAudit } from '@/lib/audit'
import { apiRoute, paginated, pagination } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { maintenanceScheduleSchema } from '@/lib/api/schemas'

export const dynamic = 'force-dynamic'

export const GET = apiRoute({ permission: 'maintenance.read' }, async ({ searchParams }) => {
  const { page, pageSize, skip, take } = pagination(searchParams, 50)
  const status = searchParams.get('status')
  const where = status ? { status } : {}

  const [items, total] = await Promise.all([
    prisma.maintenanceRecord.findMany({
      where,
      skip,
      take,
      orderBy: [{ status: 'asc' }, { scheduledAt: 'asc' }],
      include: { asset: { select: { code: true, name: true, nameAr: true } } },
    }),
    prisma.maintenanceRecord.count({ where }),
  ])

  return paginated(items, total, page, pageSize)
})

/** Raise a work order against an asset. */
export const POST = apiRoute<Record<string, string>, z.infer<typeof maintenanceScheduleSchema>>(
  { permission: 'maintenance.manage', bodySchema: maintenanceScheduleSchema },
  async ({ body, user, request }) => {
    const asset = await prisma.asset.findUnique({
      where: { code: body.assetCode },
      select: { id: true, code: true, healthScore: true },
    })
    if (!asset) throw new ApiError(ERROR_CODES.notFound)

    const record = await prisma.maintenanceRecord.create({
      data: {
        code: `WO-${Date.now().toString(36).toUpperCase()}`,
        assetId: asset.id,
        kind: body.kind,
        status: 'scheduled',
        priority: body.priority,
        scheduledAt: new Date(body.scheduledAt),
        technicianId: user.id,
        findings: body.findings ?? 'Raised from the predictive maintenance worklist.',
        findingsAr: body.findings ?? 'أُنشئ من قائمة الصيانة التنبؤية.',
        actions: 'Pending',
        actionsAr: 'قيد الانتظار',
        healthBefore: asset.healthScore,
        healthAfter: asset.healthScore,
      },
    })

    await writeAudit({
      action: AUDIT_ACTIONS.maintenanceScheduled,
      entity: 'maintenance_record',
      entityId: record.id,
      user,
      request,
      after: { assetCode: asset.code, kind: body.kind, scheduledAt: body.scheduledAt },
    })

    return record
  },
)
