import { ExperienceScoreAggregationMode } from "@prisma/client";
import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import {
  canAccessExperienciometro,
  canConfigureExperienciometro,
  ensureExperienceBaseline,
  getActiveExperiencePolicy,
  mapExperiencePolicy,
  stringifyRecentWeights,
} from "@/lib/experienciometro";
import type { ExperienceScoringPolicyPatchPayload } from "@/lib/experienciometro/types";

function toAggregationMode(value: string | undefined): ExperienceScoreAggregationMode | null {
  if (value === "weighted_recent" || value === "moving_average" || value === "full_average") {
    return value;
  }

  return null;
}

export async function GET() {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  if (!canAccessExperienciometro(session.user.role)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  await ensureExperienceBaseline(prisma, session.user.id);

  const policy = await getActiveExperiencePolicy(prisma);
  return NextResponse.json({
    ok: true,
    policy: mapExperiencePolicy(policy),
  });
}

export async function PATCH(request: Request) {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  if (!canConfigureExperienciometro(session.user.role)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  await ensureExperienceBaseline(prisma, session.user.id);

  const active = await getActiveExperiencePolicy(prisma);
  const body = (await request.json()) as ExperienceScoringPolicyPatchPayload;

  const aggregationMode = body.aggregationMode ? toAggregationMode(body.aggregationMode) : null;
  if (body.aggregationMode && !aggregationMode) {
    return NextResponse.json({ error: "Invalid aggregationMode." }, { status: 400 });
  }

  const recentWindow = body.recentWindow !== undefined ? Math.max(1, Math.floor(body.recentWindow)) : undefined;

  let recentWeightsCsv: string | undefined;
  if (body.recentWeights) {
    const validWeights = body.recentWeights.filter((value) => Number.isFinite(value) && value > 0);
    if (validWeights.length === 0) {
      return NextResponse.json({ error: "recentWeights must include positive values." }, { status: 400 });
    }

    recentWeightsCsv = stringifyRecentWeights(validWeights);
  }

  if (body.greenThreshold !== undefined && body.yellowThreshold !== undefined && body.greenThreshold <= body.yellowThreshold) {
    return NextResponse.json({ error: "greenThreshold must be greater than yellowThreshold." }, { status: 400 });
  }

  const policy = await prisma.$transaction(async (tx) => {
    if (body.isActive === true) {
      await tx.experienceScoringPolicy.updateMany({
        where: {
          id: { not: active.id },
        },
        data: {
          isActive: false,
        },
      });
    }

    return tx.experienceScoringPolicy.update({
      where: { id: active.id },
      data: {
        ...(typeof body.name === "string" ? { name: body.name.trim() || active.name } : {}),
        ...(aggregationMode ? { aggregationMode } : {}),
        ...(recentWindow !== undefined ? { recentWindow } : {}),
        ...(recentWeightsCsv ? { recentWeightsCsv } : {}),
        ...(typeof body.greenThreshold === "number" ? { greenThreshold: body.greenThreshold } : {}),
        ...(typeof body.yellowThreshold === "number" ? { yellowThreshold: body.yellowThreshold } : {}),
        ...(typeof body.isActive === "boolean" ? { isActive: body.isActive } : {}),
      },
    });
  });

  return NextResponse.json({
    ok: true,
    policy: mapExperiencePolicy(policy),
  });
}
