import { NextRequest, NextResponse } from "next/server";

export const runtime = "edge";

type CategoriaDocument = {
  $id: string;
  nome: string;
  descricao?: string;
  slug?: string;
  [key: string]: unknown;
};

type AppwriteConfig = {
  endpoint?: string;
  projectId?: string;
  databaseId?: string;
  collectionId?: string;
  apiKey?: string;
};

const FALLBACK_CATEGORIES: CategoriaDocument[] = [
  {
    $id: "cat-fallback-dor",
    nome: "Analgesicos",
    descricao: "Produtos indicados para alivio de dor",
    slug: "analgesicos",
  },
  {
    $id: "cat-fallback-vitam",
    nome: "Vitaminas",
    descricao: "Suplementos e multivitaminicos",
    slug: "vitaminas",
  },
  {
    $id: "cat-fallback-higiene",
    nome: "Higiene",
    descricao: "Itens de higiene pessoal",
    slug: "higiene",
  },
];

function readAppwriteConfig(): AppwriteConfig {
  return {
    endpoint: process.env.APPWRITE_ENDPOINT || process.env.NEXT_PUBLIC_APPWRITE_ENDPOINT,
    projectId: process.env.APPWRITE_PROJECT_ID || process.env.NEXT_PUBLIC_APPWRITE_PROJECT_ID,
    databaseId: process.env.APPWRITE_DATABASE_ID || process.env.NEXT_PUBLIC_APPWRITE_DATABASE_ID,
    collectionId:
      process.env.APPWRITE_COLLECTION_CATEGORIAS_ID ||
      process.env.NEXT_PUBLIC_APPWRITE_COLLECTION_CATEGORIAS_ID,
    apiKey: process.env.APPWRITE_API_KEY,
  };
}

function respondWithFallbackList(
  reason: string,
  params?: { term?: string; limit: number; page: number }
) {
  const { term, limit, page } = params ?? { limit: FALLBACK_CATEGORIES.length, page: 1 };
  const normalizedTerm = term?.toLowerCase().trim();

  const filtered = normalizedTerm
    ? FALLBACK_CATEGORIES.filter((categoria) =>
        categoria.nome.toLowerCase().includes(normalizedTerm) ||
        categoria.descricao?.toLowerCase().includes(normalizedTerm ?? "")
      )
    : [...FALLBACK_CATEGORIES];

  const safeLimit = Math.max(1, limit || 10);
  const start = (Math.max(1, page) - 1) * safeLimit;
  const documents = filtered.slice(start, start + safeLimit);

  console.warn("[API][categorias] Respondendo com fallback:", reason);

  return NextResponse.json(
    {
      success: true,
      categorias: documents,
      documents,
      total: filtered.length,
      fallback: true,
      source: "categorias-fallback",
      error: reason,
    },
    { status: 200 }
  );
}

function respondWithFallbackCreate(
  nome: string,
  extras: Partial<CategoriaDocument>,
  reason: string
) {
  const documento: CategoriaDocument = {
    $id: `cat-fallback-${Date.now()}`,
    nome,
    slug: extras.slug || nome.toLowerCase().replace(/\s+/g, "-"),
    ...extras,
  };

  console.warn("[API][categorias] Criando categoria em modo fallback:", reason);

  return NextResponse.json(
    {
      success: true,
      sucesso: true,
      data: documento,
      fallback: true,
      source: "categorias-fallback",
      mensagem: "Categoria criada no modo fallback",
      error: reason,
    },
    { status: 200 }
  );
}

function ensureConfig(config: AppwriteConfig) {
  const missing = Object.entries(config)
    .filter(([_, value]) => !value)
    .map(([key]) => key);

  return {
    ok: missing.length === 0,
    missing,
  } as const;
}

type ResolvedAppwriteConfig = {
  endpoint: string;
  projectId: string;
  databaseId: string;
  collectionId: string;
  apiKey: string;
};

function normalizeEndpoint(endpoint: string) {
  return endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
}

function buildAppwriteHeaders(config: ResolvedAppwriteConfig) {
  return {
    "X-Appwrite-Project": config.projectId,
    "X-Appwrite-Key": config.apiKey,
    Accept: "application/json",
  };
}

function escapeQueryValue(value: string) {
  return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
}

function buildQueries(term: string, limit: number, offset: number) {
  const queries = [`limit(${limit})`, `offset(${offset})`];
  if (term) {
    queries.unshift(`search("nome", "${escapeQueryValue(term)}")`);
  }
  return queries;
}

async function buildAppwriteError(response: Response) {
  let message = `Appwrite responded with status ${response.status}`;
  let payload: unknown;

  try {
    payload = await response.json();
    if (
      payload &&
      typeof payload === "object" &&
      "message" in payload &&
      typeof (payload as any).message === "string"
    ) {
      message = (payload as any).message;
    }
  } catch {
    // ignore json parse errors
  }

  const error = new Error(message);
  (error as any).status = response.status;
  (error as any).payload = payload;
  return error;
}

async function appwriteListDocuments(
  config: ResolvedAppwriteConfig,
  queries: string[]
): Promise<{ documents: CategoriaDocument[]; total: number }> {
  const endpoint = normalizeEndpoint(config.endpoint);
  const url = new URL(
    `${endpoint}/databases/${config.databaseId}/collections/${config.collectionId}/documents`
  );
  for (const query of queries) {
    url.searchParams.append("queries[]", query);
  }

  const response = await fetch(url.toString(), {
    method: "GET",
    headers: buildAppwriteHeaders(config),
  });

  if (!response.ok) {
    throw await buildAppwriteError(response);
  }

  return (await response.json()) as { documents: CategoriaDocument[]; total: number };
}

async function appwriteCreateDocument(
  config: ResolvedAppwriteConfig,
  data: Record<string, unknown>
): Promise<CategoriaDocument> {
  const endpoint = normalizeEndpoint(config.endpoint);
  const url = `${endpoint}/databases/${config.databaseId}/collections/${config.collectionId}/documents`;

  const response = await fetch(url, {
    method: "POST",
    headers: {
      ...buildAppwriteHeaders(config),
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      documentId: "unique()",
      data,
    }),
  });

  if (!response.ok) {
    throw await buildAppwriteError(response);
  }

  return (await response.json()) as CategoriaDocument;
}

export async function GET(request: NextRequest) {
  console.log("[API][categorias] Listando categorias...");

  const { searchParams } = new URL(request.url);
  const limitParam = Number(searchParams.get("limit"));
  const pageParam = Number(searchParams.get("page"));
  const term = (searchParams.get("termoBuscado") || "").trim();

  const safeLimit = Number.isFinite(limitParam) && limitParam > 0 ? Math.min(limitParam, 100) : 10;
  const safePage = Number.isFinite(pageParam) && pageParam > 0 ? pageParam : 1;

  try {
    const config = readAppwriteConfig();
    const { ok, missing } = ensureConfig(config);

    if (!config.apiKey || !ok) {
      const reason = !config.apiKey
        ? "APPWRITE_API_KEY ausente"
        : `Variaveis Appwrite ausentes: ${missing.join(", ")}`;
      return respondWithFallbackList(reason, { term, limit: safeLimit, page: safePage });
    }

    const resolved: ResolvedAppwriteConfig = {
      endpoint: config.endpoint as string,
      projectId: config.projectId as string,
      databaseId: config.databaseId as string,
      collectionId: config.collectionId as string,
      apiKey: config.apiKey as string,
    };

    const offset = (Math.max(1, safePage) - 1) * safeLimit;
    const queries = buildQueries(term, safeLimit, offset);

    const response = await appwriteListDocuments(resolved, queries);

    console.log(`[API][categorias] ${response.total} categorias carregadas.`);

    return NextResponse.json({
      success: true,
      categorias: response.documents,
      documents: response.documents,
      total: response.total,
    });
  } catch (error) {
    console.error("[API][categorias] Erro ao listar categorias:", error);
    const reason = error instanceof Error ? error.message : "Falha ao listar categorias";
    return respondWithFallbackList(reason, { term, limit: safeLimit, page: safePage });
  }
}

export async function POST(request: NextRequest) {
  console.log("[API][categorias] Criando categoria...");

  try {
    const body = await request.json();
    const nome: string | undefined =
      typeof body?.nome === "string" ? body.nome.trim() : undefined;

    if (!nome) {
      return NextResponse.json(
        { success: false, error: "Nome da categoria e obrigatorio" },
        { status: 400 }
      );
    }

    const config = readAppwriteConfig();
    const { ok, missing } = ensureConfig(config);

    if (!config.apiKey || !ok) {
      const reason = !config.apiKey
        ? "APPWRITE_API_KEY ausente"
        : `Variaveis Appwrite ausentes: ${missing.join(", ")}`;
      return respondWithFallbackCreate(nome, body, reason);
    }

    const resolved: ResolvedAppwriteConfig = {
      endpoint: config.endpoint as string,
      projectId: config.projectId as string,
      databaseId: config.databaseId as string,
      collectionId: config.collectionId as string,
      apiKey: config.apiKey as string,
    };

    const dadosCategoria: Record<string, unknown> = {
      nome,
      descricao: typeof body.descricao === "string" ? body.descricao.trim() || "" : "",
      slug:
        typeof body.slug === "string" && body.slug.trim().length > 0
          ? body.slug.trim()
          : nome.toLowerCase().replace(/\s+/g, "-"),
    };

    try {
      const novaCategoria = await appwriteCreateDocument(resolved, dadosCategoria);

      console.log("[API][categorias] Categoria criada com sucesso");
      return NextResponse.json({
        success: true,
        sucesso: true,
        data: novaCategoria,
        mensagem: "Categoria criada com sucesso",
      });
    } catch (createError) {
      console.warn(
        "[API][categorias] Falha na primeira tentativa, tentando modo simplificado:",
        createError
      );

      try {
        const novaCategoria = await appwriteCreateDocument(resolved, { nome });

        console.log(
          "[API][categorias] Categoria criada com sucesso (modo simplificado)"
        );
        return NextResponse.json({
          success: true,
          sucesso: true,
          data: novaCategoria,
          mensagem: "Categoria criada com sucesso (modo simplificado)",
        });
      } catch (secondError) {
        console.error("[API][categorias] Segunda tentativa falhou:", secondError);
        const reason =
          secondError instanceof Error
            ? secondError.message
            : "Falha ao criar categoria";
        return respondWithFallbackCreate(nome, dadosCategoria, reason);
      }
    }
  } catch (error) {
    console.error("[API][categorias] Erro inesperado na criacao:", error);

    if (error instanceof Error && (error as any)?.status) {
      const details = (error as any).payload;
      const statusCode =
        typeof (error as any).status === "number" &&
        (error as any).status >= 400 &&
        (error as any).status < 600
          ? (error as any).status
          : 500;

      return NextResponse.json(
        {
          success: false,
          error: `Erro do Appwrite: ${error.message}`,
          details,
        },
        { status: statusCode }
      );
    }

    const reason = error instanceof Error ? error.message : "Falha na criacao";
    return NextResponse.json({ success: false, error: reason }, { status: 500 });
  }
}
