import { NextRequest, NextResponse } from 'next/server';
import { courses } from '@/db/schema';
import {
  AUDIT_ACTION,
  AUDIT_MODULE,
  getRequestMetadata,
  logAuditEvent,
  toAuditValue
} from '@/features/audit-logs/server/audit-service';
import type { CourseMutationPayload } from '@/features/courses/api/types';
import {
  listCoursesForOrganization,
  normalizeCoursePayload,
  serializeCourse
} from '@/features/courses/server/course-data';
import { isHRD } from '@/lib/auth/roles';
import { AuthError, requireHRD, requireOrganizationAccess } from '@/lib/auth/session';
import { db } from '@/lib/db';

function getSingleFilterParam(
  searchParams: URLSearchParams,
  primaryKey: string,
  legacyKey?: string
) {
  const rawValue = searchParams.get(primaryKey) ?? (legacyKey ? searchParams.get(legacyKey) : null);
  const normalized = rawValue
    ?.split(/[.,]/)
    .map((value) => value.trim())
    .find(Boolean);

  return normalized && normalized !== 'all' ? normalized : undefined;
}

export async function GET(request: NextRequest) {
  try {
    const access = await requireOrganizationAccess();
    const { searchParams } = request.nextUrl;
    const canManageCourses = isHRD({
      businessRole: access.session.user.businessRole,
      systemRole: access.session.user.systemRole,
      membershipRole: access.membership.role,
      role: access.session.user.role
    });
    const requestedStatus = getSingleFilterParam(searchParams, 'status', 'statuses');

    const result = await listCoursesForOrganization({
      organizationId: access.organization.id,
      filters: {
        page: Number(searchParams.get('page') ?? 1),
        limit: Number(searchParams.get('limit') ?? 10),
        search: searchParams.get('search') ?? undefined,
        category: getSingleFilterParam(searchParams, 'category', 'categories'),
        status: canManageCourses ? requestedStatus : 'active',
        sort: searchParams.get('sort') ?? undefined
      }
    });

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'โหลดหลักสูตรเรียบร้อยแล้ว',
      total_courses: result.total,
      offset: result.offset,
      limit: result.limit,
      courses: result.courses
    });
  } 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 } = await requireHRD();
    const requestMetadata = getRequestMetadata(request);
    const body = normalizeCoursePayload((await request.json()) as CourseMutationPayload);

    const [course] = await db
      .insert(courses)
      .values({
        organizationId: organization.id,
        courseCode: body.courseCode,
        name: body.name,
        category: body.category,
        organizer: body.organizer,
        standardHours: body.standardHours,
        certificateValidityMonths: body.certificateValidityMonths,
        isRequired: body.isRequired,
        certificateRequired: true,
        trainingCost: body.trainingCost,
        description: body.description,
        isActive: body.isActive
      })
      .returning();

    const serializedCourse = serializeCourse(course);

    await logAuditEvent({
      organizationId: organization.id,
      userId: session.user.id,
      module: AUDIT_MODULE.COURSE_MASTER,
      action: AUDIT_ACTION.CREATE,
      entityName: course.name,
      entityId: course.id,
      newValue: toAuditValue(serializedCourse),
      ...requestMetadata
    });

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

    return NextResponse.json({ message: 'ไม่สามารถสร้างหลักสูตรได้' }, { status: 500 });
  }
}
