import { NextRequest, NextResponse } from 'next/server';
import { trainingRecords } from '@/db/schema';
import {
  AUDIT_ACTION,
  AUDIT_MODULE,
  getRequestMetadata,
  logAuditEvent,
  toAuditValue
} from '@/features/audit-logs/server/audit-service';
import type { TrainingRecordMutationPayload } from '@/features/training-records/api/types';
import {
  assertUserAndCourseAccess,
  isMissingTrainingRecordMinutesStorage,
  listTrainingRecordsForOrganization,
  normalizeTrainingRecordPayload,
  serializeTrainingRecord
} from '@/features/training-records/server/training-record-data';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';
import { getDatabaseErrorMessage } from '@/lib/db-errors';
import { db } from '@/lib/db';

function getFilterParam(searchParams: URLSearchParams, ...keys: string[]) {
  for (const key of keys) {
    const value = searchParams.get(key)?.trim();
    if (value && value !== 'all') {
      return value;
    }
  }

  return undefined;
}

export async function GET(request: NextRequest) {
  try {
    const { organization, session, membership } = await requireOrganizationAccess();
    const { searchParams } = request.nextUrl;

    const result = await listTrainingRecordsForOrganization({
      organizationId: organization.id,
      userId: session.user.id,
      role: membership.role,
      filters: {
        page: Number(searchParams.get('page') ?? 1),
        limit: Number(searchParams.get('limit') ?? 10),
        search: getFilterParam(searchParams, 'search', 'user_name', 'name'),
        statuses: getFilterParam(searchParams, 'statuses', 'approval_status', 'status'),
        types: getFilterParam(searchParams, 'types', 'training_type', 'type'),
        year: getFilterParam(searchParams, 'year'),
        company: getFilterParam(searchParams, 'company'),
        department: getFilterParam(searchParams, 'department'),
        sort: searchParams.get('sort') ?? undefined
      }
    });

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'โหลดประวัติการอบรมเรียบร้อยแล้ว',
      total_training_records: result.total,
      offset: result.offset,
      limit: result.limit,
      training_records: result.trainingRecords
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    return NextResponse.json({ message: 'ไม่สามารถโหลดประวัติการอบรมได้' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const { organization, session, membership } = await requireOrganizationAccess();
    const requestMetadata = getRequestMetadata(request);
    const body = normalizeTrainingRecordPayload(
      (await request.json()) as TrainingRecordMutationPayload
    );
    const approvalStatus = body.submissionMode === 'draft' ? 'draft' : 'pending';

    const { user, course } = await assertUserAndCourseAccess({
      organizationId: organization.id,
      targetEmployeeId: body.employeeId,
      actorUserId: session.user.id,
      actorRole: membership.role,
      courseId: body.courseId,
      courseName: body.courseName
    });

    if (!user || !course) {
      if (!user) {
        return NextResponse.json(
          { message: 'ไม่พบผู้ใช้งานในองค์กรที่กำลังใช้งานอยู่' },
          { status: 400 }
        );
      }
    }

    let record;

    try {
      [record] = await db
        .insert(trainingRecords)
        .values({
          organizationId: organization.id,
          userId: user.userId ?? null,
          employeeId: body.employeeId,
          courseId: course?.id ?? null,
          courseName: course?.name ?? body.courseName,
          trainingDate: new Date(body.trainingDate),
          trainingType: body.trainingType,
          submittedMinutes: body.submittedMinutes,
          hours: body.hours,
          organizer: body.organizer,
          note: body.note,
          approvalStatus,
          submittedByUserId: session.user.id,
          createdBy: session.user.id
        })
        .returning();
    } catch (error) {
      if (!isMissingTrainingRecordMinutesStorage(error)) {
        throw error;
      }

      [record] = await db
        .insert(trainingRecords)
        .values({
          organizationId: organization.id,
          userId: user.userId ?? null,
          employeeId: body.employeeId,
          courseId: course?.id ?? null,
          courseName: course?.name ?? body.courseName,
          trainingDate: new Date(body.trainingDate),
          trainingType: body.trainingType,
          hours: body.hours,
          organizer: body.organizer,
          note: body.note,
          approvalStatus,
          submittedByUserId: session.user.id,
          createdBy: session.user.id
        })
        .returning();
    }

    const serializedRecord = serializeTrainingRecord({
      id: record.id,
      organizationId: record.organizationId,
      userId: record.userId,
      employeeId: record.employeeId,
      employeeCode: user.employeeCode ?? null,
      userName: user.fullName,
      companyName: user.companyName,
      departmentName: null,
      courseId: record.courseId,
      courseName: record.courseName,
      trainingDate: record.trainingDate,
      trainingType: record.trainingType,
      submittedMinutes: record.submittedMinutes,
      hours: record.hours,
      approvedMinutes: record.approvedMinutes,
      approvedHours: record.approvedHours,
      category: record.category,
      organizer: record.organizer,
      note: record.note,
      certificatePreviewUrl: null,
      certificatePreviewType: null,
      approvalStatus: record.approvalStatus,
      reviewerNote: record.reviewerNote,
      rejectReason: record.rejectReason,
      reviewedBy: record.reviewedBy,
      reviewedAt: record.reviewedAt,
      createdBy: record.createdBy,
      createdByName: session.user.name ?? null,
      createdAt: record.createdAt,
      updatedAt: record.updatedAt
    });

    await logAuditEvent({
      organizationId: organization.id,
      userId: session.user.id,
      module: AUDIT_MODULE.TRAINING_RECORDS,
      action: AUDIT_ACTION.CREATE,
      entityName: record.courseName,
      entityId: record.id,
      newValue: toAuditValue(serializedRecord),
      ...requestMetadata
    });

    return NextResponse.json(
      {
        success: true,
        time: new Date().toISOString(),
        message: 'สร้างรายการอบรมเรียบร้อยแล้ว',
        training_record: serializedRecord
      },
      { status: 201 }
    );
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    console.error('Failed to create training record', error);
    return NextResponse.json({ message: getDatabaseErrorMessage(error) }, { status: 500 });
  }
}
