/* eslint-disable no-eval */
import { NextRequest, NextResponse } from "next/server";
const fs = eval('require("fs")') as typeof import("fs");
const path = eval('require("path")') as typeof import("path");
import { getBotDataDir } from "@/lib/paths";

interface Code {
  id?: string;
  code: string;
  reward?: string;
  uses?: number;
  maxUses?: number;
  createdAt?: string;
  expiresAt?: string;
  [key: string]: unknown;
}

function getCodigosPath(): string {
  return path.join(getBotDataDir("bot_comunidade"), "codigos.json");
}

function readCodigos(): Code[] {
  const filePath = getCodigosPath();
  try {
    if (!fs.existsSync(filePath)) {
      return [];
    }
    const content = fs.readFileSync(filePath, "utf-8");
    const data = JSON.parse(content);
    return Array.isArray(data) ? data : data.codigos || [];
  } catch {
    return [];
  }
}

function writeCodigos(codigos: Code[]): void {
  const filePath = getCodigosPath();
  const dir = path.dirname(filePath);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
  fs.writeFileSync(filePath, JSON.stringify(codigos, null, 2), "utf-8");
}

export async function GET() {
  try {
    const codigos = readCodigos();
    return NextResponse.json({ codigos, total: codigos.length });
  } catch (error) {
    return NextResponse.json(
      {
        error: `Failed to read codes: ${error instanceof Error ? error.message : String(error)}`,
      },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();

    if (!body.code || typeof body.code !== "string") {
      return NextResponse.json(
        { success: false, error: "Missing or invalid 'code' field" },
        { status: 400 }
      );
    }

    const codigos = readCodigos();

    // Check for duplicates
    if (codigos.some((c) => c.code === body.code)) {
      return NextResponse.json(
        { success: false, error: `Code '${body.code}' already exists` },
        { status: 409 }
      );
    }

    const newCode: Code = {
      id: `code_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`,
      code: body.code,
      reward: body.reward || "",
      uses: 0,
      maxUses: body.maxUses || 0,
      createdAt: new Date().toISOString(),
      expiresAt: body.expiresAt || null,
    };

    codigos.push(newCode);
    writeCodigos(codigos);

    return NextResponse.json({
      success: true,
      code: newCode,
      message: `Code '${newCode.code}' created successfully.`,
    });
  } catch (error) {
    return NextResponse.json(
      {
        success: false,
        error: `Failed to create code: ${error instanceof Error ? error.message : String(error)}`,
      },
      { status: 500 }
    );
  }
}

export async function DELETE(request: NextRequest) {
  try {
    const body = await request.json();
    const codeToDelete = body.code || body.id;

    if (!codeToDelete) {
      return NextResponse.json(
        { success: false, error: "Missing 'code' or 'id' field" },
        { status: 400 }
      );
    }

    const codigos = readCodigos();
    const index = codigos.findIndex(
      (c) => c.code === codeToDelete || c.id === codeToDelete
    );

    if (index === -1) {
      return NextResponse.json(
        { success: false, error: `Code '${codeToDelete}' not found` },
        { status: 404 }
      );
    }

    const removed = codigos.splice(index, 1)[0];
    writeCodigos(codigos);

    return NextResponse.json({
      success: true,
      removed,
      message: `Code '${removed.code}' deleted successfully.`,
    });
  } catch (error) {
    return NextResponse.json(
      {
        success: false,
        error: `Failed to delete code: ${error instanceof Error ? error.message : String(error)}`,
      },
      { status: 500 }
    );
  }
}
