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

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

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

// GET - Récupérer les données d'un client par son token
export async function GET(
  request: NextRequest,
  { params }: { params: { token: string } }
) {
  try {
    const clients = await loadClients();
    const client = clients.find(c => c.token === params.token);
    
    if (!client) {
      return NextResponse.json(
        { error: "Client non trouvé" },
        { status: 404 }
      );
    }

    // Retourner uniquement les données nécessaires (pas le token ni l'ID)
    return NextResponse.json({
      bungalowNumber: client.bungalowNumber,
      wifiName: client.wifiName,
      wifiPassword: client.wifiPassword,
      gerantMessage: client.gerantMessage,
    });
  } catch (error) {
    console.error("Erreur GET client par token:", error);
    return NextResponse.json(
      { error: "Erreur serveur" },
      { status: 500 }
    );
  }
}

