import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import {
  getAutoPlacement,
  getPositionLabel,
  SPECIAL_CARD_TEAM_LIMIT,
} from "@/lib/specialCards";

export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const session = await getServerSession(authOptions);
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const userId = (session.user as any).id;
  const { id } = await params;
  const { replacePlayerId } = await req.json().catch(() => ({}));

  const team = await db.team.findUnique({
    where: { userId },
    include: {
      players: {
        include: {
          player: true,
          goldenCard: true,
        },
      },
    },
  });
  if (!team) return NextResponse.json({ error: "ابتدا تیم بساز" }, { status: 400 });

  const card = await db.goldenCard.findUnique({
    where: { id },
    include: {
      player: { include: { country: true } },
      teamPlayer: true,
    },
  });
  if (!card) return NextResponse.json({ error: "کارت ویژه پیدا نشد" }, { status: 404 });
  if (card.userId !== userId) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  if (card.status !== "OPENED") return NextResponse.json({ error: "ابتدا کارت را باز کنید" }, { status: 400 });
  if (card.state === "SOLD") return NextResponse.json({ error: "این کارت فروخته شده است" }, { status: 400 });
  if (card.state === "IN_TEAM") return NextResponse.json({ error: "این کارت همین حالا در تیم است" }, { status: 400 });

  const existingSpecialCount = team.players.filter((item) => item.goldenCardId).length;
  const sameCountry = team.players.filter((item) => item.player.countryId === card.player.countryId).length;
  const existingPlayer = team.players.find((item) => item.playerId === card.playerId);

  if (!existingPlayer && sameCountry >= 3) {
    return NextResponse.json({ error: "حداکثر 3 بازیکن از یک تیم ملی" }, { status: 400 });
  }

  if (existingPlayer) {
    if (existingPlayer.goldenCardId) {
      return NextResponse.json({ error: "نسخه ویژه این بازیکن در تیم شما وجود دارد" }, { status: 400 });
    }
    if (existingSpecialCount >= SPECIAL_CARD_TEAM_LIMIT) {
      return NextResponse.json({ error: "ظرفیت 3 کارت ویژه تیم پر است" }, { status: 400 });
    }

    const updatedTeamPlayer = await db.$transaction(async (tx) => {
      const updatedPlayer = await tx.teamPlayer.update({
        where: { teamId_playerId: { teamId: team.id, playerId: existingPlayer.playerId } },
        data: { goldenCardId: card.id },
      });

      await tx.goldenCard.update({
        where: { id: card.id },
        data: { state: "IN_TEAM" },
      });

      return updatedPlayer;
    });

    return NextResponse.json({
      success: true,
      action: "converted_existing",
      placement: existingPlayer.isBench ? "ذخیره" : "فیکس",
      teamPlayer: updatedTeamPlayer,
      card: { ...card, state: "IN_TEAM" },
      message: "بازیکن موجود تیم شما به نسخه ویژه تبدیل شد",
    });
  }

  const autoPlacement = getAutoPlacement(team.formation, team.players as any, card.player.position);

  if (!replacePlayerId && !autoPlacement) {
    const candidates = team.players
      .filter((item) => item.player.position === card.player.position)
      .map((item) => ({
        playerId: item.playerId,
        name: item.player.name,
        isBench: item.isBench,
        isSpecial: Boolean(item.goldenCardId),
      }));

    return NextResponse.json(
      {
        error: `پست ${getPositionLabel(card.player.position)} در ترکیب اصلی و ذخیره پر است`,
        needsReplacement: true,
        candidates,
      },
      { status: 409 }
    );
  }

  const replacingPlayer = replacePlayerId
    ? team.players.find((item) => item.playerId === replacePlayerId)
    : null;

  if (replacePlayerId && (!replacingPlayer || replacingPlayer.player.position !== card.player.position)) {
    return NextResponse.json({ error: "بازیکن انتخاب‌شده برای تعویض معتبر نیست" }, { status: 400 });
  }

  const nextSpecialCount = existingSpecialCount + 1 - (replacingPlayer?.goldenCardId ? 1 : 0);
  if (nextSpecialCount > SPECIAL_CARD_TEAM_LIMIT) {
    return NextResponse.json({ error: "ظرفیت 3 کارت ویژه تیم پر است" }, { status: 400 });
  }

  if (!replacingPlayer && team.players.length >= 15) {
    return NextResponse.json({ error: "تیم پر است" }, { status: 400 });
  }

  const result = await db.$transaction(async (tx) => {
    if (replacingPlayer) {
      await tx.teamPlayer.delete({
        where: { teamId_playerId: { teamId: team.id, playerId: replacingPlayer.playerId } },
      });

      if (replacingPlayer.goldenCardId) {
        await tx.goldenCard.update({
          where: { id: replacingPlayer.goldenCardId },
          data: { state: "IN_INVENTORY" },
        });
      }
    }

    const teamPlayer = await tx.teamPlayer.create({
      data: {
        teamId: team.id,
        playerId: card.playerId,
        goldenCardId: card.id,
        isBench: replacingPlayer ? replacingPlayer.isBench : autoPlacement!.isBench,
      },
    });

    await tx.goldenCard.update({
      where: { id: card.id },
      data: { state: "IN_TEAM" },
    });

    return teamPlayer;
  });

  const placement = replacingPlayer
    ? replacingPlayer.isBench
      ? "ذخیره"
      : "فیکس"
    : autoPlacement!.placementLabel;

  return NextResponse.json({
    success: true,
    action: replacingPlayer ? "replaced" : "added",
    placement,
    replacedPlayerId: replacingPlayer?.playerId ?? null,
    replacedGoldenCardId: replacingPlayer?.goldenCardId ?? null,
    card: { ...card, state: "IN_TEAM" },
    teamPlayer: result,
    message: replacingPlayer
      ? "بازیکن ویژه جایگزین بازیکن انتخاب‌شده شد"
      : `بازیکن ویژه به صورت خودکار در ${placement} قرار گرفت`,
  });
}
