/* 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 Streamer {
  id?: string;
  name: string;
  platform?: string;
  channelId?: string;
  notifyChannel?: string;
  addedAt?: string;
  [key: string]: unknown;
}

function getStreamersPath(): string {
  return path.join(getBotDataDir("bot_utilidades"), "streamers.json");
}

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

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

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

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

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

    const streamers = readStreamers();

    // Check for duplicates
    if (
      streamers.some(
        (s) => s.name.toLowerCase() === body.name.toLowerCase()
      )
    ) {
      return NextResponse.json(
        { success: false, error: `Streamer '${body.name}' already exists` },
        { status: 409 }
      );
    }

    const newStreamer: Streamer = {
      id: `streamer_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`,
      name: body.name,
      platform: body.platform || "twitch",
      channelId: body.channelId || "",
      notifyChannel: body.notifyChannel || "",
      addedAt: new Date().toISOString(),
    };

    streamers.push(newStreamer);
    writeStreamers(streamers);

    return NextResponse.json({
      success: true,
      streamer: newStreamer,
      message: `Streamer '${newStreamer.name}' added successfully.`,
    });
  } catch (error) {
    return NextResponse.json(
      {
        success: false,
        error: `Failed to add streamer: ${error instanceof Error ? error.message : String(error)}`,
      },
      { status: 500 }
    );
  }
}

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

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

    const streamers = readStreamers();
    const index = streamers.findIndex(
      (s) =>
        s.name.toLowerCase() === identifier.toLowerCase() ||
        s.id === identifier
    );

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

    const removed = streamers.splice(index, 1)[0];
    writeStreamers(streamers);

    return NextResponse.json({
      success: true,
      removed,
      message: `Streamer '${removed.name}' removed successfully.`,
    });
  } catch (error) {
    return NextResponse.json(
      {
        success: false,
        error: `Failed to remove streamer: ${error instanceof Error ? error.message : String(error)}`,
      },
      { status: 500 }
    );
  }
}
