import { NextRequest, NextResponse } from 'next/server';
import { trainingPolicies } from '@/db/schema';
import {
  AUDIT_ACTION,
  AUDIT_MODULE,
  getRequestMetadata,
  logAuditEvent,
  toAuditValue
} from '@/features/audit-logs/server/audit-service';
import {
  getNextTrainingPolicyYearForClone,
  getTrainingPolicyByIdForOrganization,
  serializeTrainingPolicy
} from '@/features/training-policy/server/training-policy-data';
import { AuthError, requirePermission } from '@/lib/auth/session';
import { db } from '@/lib/db';

type Params = { params: Promise<{ id: string }> };

export async function POST(request: NextRequest, { params }: Params) {
  try {
    const { organization, session } = await requirePermission('training_policy:write');
    const requestMetadata = getRequestMetadata(request);
    const { id } = await params;
    const policyId = Number(id);
    const sourcePolicy = await getTrainingPolicyByIdForOrganization({
      id: policyId,
      organizationId: organization.id
    });

    if (!sourcePolicy) {
      return NextResponse.json(
        { success: false, message: `ไม่พบนโยบายการอบรมรหัส ${id}` },
        { status: 404 }
      );
    }

    const nextYear = await getNextTrainingPolicyYearForClone({
      organizationId: organization.id,
      baseYear: sourcePolicy.year
    });

    const [clonedPolicy] = await db
      .insert(trainingPolicies)
      .values({
        organizationId: organization.id,
        year: nextYear,
        totalHours: sourcePolicy.totalHours,
        kHours: sourcePolicy.kHours,
        sHours: sourcePolicy.sHours,
        aHours: sourcePolicy.aHours,
        isActive: false
      })
      .returning();

    const serializedPolicy = serializeTrainingPolicy(clonedPolicy, {
      updatedByName: session.user.name ?? null
    });

    await logAuditEvent({
      organizationId: organization.id,
      userId: session.user.id,
      module: AUDIT_MODULE.TRAINING_POLICY,
      action: AUDIT_ACTION.CLONE,
      entityName: `ปี ${clonedPolicy.year}`,
      entityId: clonedPolicy.id,
      oldValue: toAuditValue(serializeTrainingPolicy(sourcePolicy)),
      newValue: toAuditValue(serializedPolicy),
      ...requestMetadata
    });

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'โคลนนโยบายการอบรมเรียบร้อยแล้ว',
      policy_id: clonedPolicy.id
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    console.error('POST /api/training-policies/[id]/clone failed', error);
    return NextResponse.json({ message: 'ไม่สามารถโคลนนโยบายการอบรมได้' }, { status: 500 });
  }
}
