import { NextRequest, NextResponse } from "next/server";
import { writeFile, readFile, mkdir } from "fs/promises";
import { existsSync } from "fs";
import path from "path";
import { Client, ClientInput } from "@/lib/types/client";

const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || "admin123";
const DATA_DIR = path.join(process.cwd(), "data");
const CLIENTS_FILE = path.join(DATA_DIR, "clients.json");

function verifyAuth(request: NextRequest): boolean {
  const authHeader = request.headers.get("authorization");
  if (!authHeader) return false;
  
  const token = authHeader.replace("Bearer ", "");
  return token === ADMIN_PASSWORD;
}

async function loadClients(): Promise<Client[]> {
  try {
    if (!existsSync(CLIENTS_FILE)) {
      if (!existsSync(DATA_DIR)) {
        await mkdir(DATA_DIR, { recursive: true });
      }
      await writeFile(CLIENTS_FILE, JSON.stringify([], null, 2));
      return [];
    }
    
    const data = await readFile(CLIENTS_FILE, "utf-8");
    return JSON.parse(data);
  } catch (error) {
    console.error("Erreur lecture clients:", error);
    return [];
  }
}

async function saveClients(clients: Client[]): Promise<void> {
  try {
    if (!existsSync(DATA_DIR)) {
      await mkdir(DATA_DIR, { recursive: true });
    }
    await writeFile(CLIENTS_FILE, JSON.stringify(clients, null, 2));
  } catch (error) {
    console.error("Erreur sauvegarde clients:", error);
    throw error;
  }
}

// GET - Récupérer un client par ID
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  if (!verifyAuth(request)) {
    return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
  }

  try {
    const clients = await loadClients();
    const client = clients.find(c => c.id === params.id);
    
    if (!client) {
      return NextResponse.json(
        { error: "Client non trouvé" },
        { status: 404 }
      );
    }

    return NextResponse.json(client);
  } catch (error) {
    console.error("Erreur GET client:", error);
    return NextResponse.json(
      { error: "Erreur serveur" },
      { status: 500 }
    );
  }
}

// PUT - Mettre à jour un client
export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  if (!verifyAuth(request)) {
    return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
  }

  try {
    const input: ClientInput = await request.json();
    const clients = await loadClients();
    const clientIndex = clients.findIndex(c => c.id === params.id);
    
    if (clientIndex === -1) {
      return NextResponse.json(
        { error: "Client non trouvé" },
        { status: 404 }
      );
    }

    // Mettre à jour le client
    const updatedClient: Client = {
      ...clients[clientIndex],
      email: input.email || clients[clientIndex].email,
      bungalowNumber: input.bungalowNumber || clients[clientIndex].bungalowNumber,
      wifiName: input.wifiName || clients[clientIndex].wifiName,
      wifiPassword: input.wifiPassword || clients[clientIndex].wifiPassword,
      gerantMessage: input.gerantMessage || clients[clientIndex].gerantMessage,
    };

    clients[clientIndex] = updatedClient;
    await saveClients(clients);

    return NextResponse.json(updatedClient);
  } catch (error) {
    console.error("Erreur PUT client:", error);
    return NextResponse.json(
      { error: "Erreur serveur" },
      { status: 500 }
    );
  }
}

// DELETE - Supprimer un client
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  if (!verifyAuth(request)) {
    return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
  }

  try {
    const clients = await loadClients();
    const filteredClients = clients.filter(c => c.id !== params.id);
    
    if (filteredClients.length === clients.length) {
      return NextResponse.json(
        { error: "Client non trouvé" },
        { status: 404 }
      );
    }

    await saveClients(filteredClients);
    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Erreur DELETE client:", error);
    return NextResponse.json(
      { error: "Erreur serveur" },
      { status: 500 }
    );
  }
}

