import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";

// Validation schema for logo generation request
const generateLogoSchema = z.object({
  projectId: z.string(),
  companyName: z.string().min(1).max(100),
  style: z.enum(["modern", "minimalist", "vintage", "playful", "professional", "abstract", "geometric", "organic"]),
  colors: z.array(z.string()).min(1).max(5),
  description: z.string().max(500).optional(),
  industry: z.string().optional(),
  mood: z.array(z.string()).optional(),
});

type LogoGenerationRequest = z.infer<typeof generateLogoSchema>;

// DALL-E 3 API integration
async function generateLogoWithDallE(params: LogoGenerationRequest): Promise<string> {
  const apiKey = process.env.OPENAI_API_KEY;

  if (!apiKey) {
    throw new Error("OpenAI API key not configured. Please add OPENAI_API_KEY to your environment variables.");
  }

  // Build comprehensive prompt for DALL-E 3
  const colorList = params.colors.join(", ");
  const moodText = params.mood?.length ? ` with a ${params.mood.join(", ")} mood` : "";
  const industryText = params.industry ? ` for the ${params.industry} industry` : "";
  const additionalDesc = params.description ? ` ${params.description}` : "";

  const prompt = `Create a professional logo design for "${params.companyName}".
Style: ${params.style}
Colors: ${colorList}${industryText}${moodText}.${additionalDesc}
The logo should be clean, scalable, and memorable. Design it on a transparent or white background, perfectly centered, ready for use as a brand identity. High quality, professional logo design.`;

  console.log("Generating logo with prompt:", prompt);

  try {
    const response = await fetch("https://api.openai.com/v1/images/generations", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${apiKey}`,
      },
      body: JSON.stringify({
        model: "dall-e-3",
        prompt: prompt,
        n: 1,
        size: "1024x1024",
        quality: "standard",
        response_format: "url",
      }),
    });

    if (!response.ok) {
      const error = await response.json();
      console.error("DALL-E API error:", error);
      throw new Error(error.error?.message || "Failed to generate logo");
    }

    const data = await response.json();

    if (!data.data || !data.data[0] || !data.data[0].url) {
      throw new Error("Invalid response from DALL-E API");
    }

    return data.data[0].url;
  } catch (error) {
    console.error("Error calling DALL-E API:", error);
    throw error;
  }
}

// POST /api/ai/generate-logo - Generate logo using DALL-E 3
export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const validated = generateLogoSchema.parse(body);

    // Generate logo with DALL-E 3
    const logoUrl = await generateLogoWithDallE(validated);

    // TODO: In production, download the image and store it in your storage
    // For now, we'll return the temporary DALL-E URL (expires after some time)
    // You should implement proper storage (S3, Cloudinary, etc.)

    return NextResponse.json({
      success: true,
      logoUrl,
      message: "Logo generated successfully!",
    });

  } catch (error) {
    console.error("Error generating logo:", error);

    if (error instanceof z.ZodError) {
      return NextResponse.json(
        {
          success: false,
          error: "Invalid input",
          details: error.errors
        },
        { status: 400 }
      );
    }

    if (error instanceof Error) {
      return NextResponse.json(
        {
          success: false,
          error: error.message
        },
        { status: 500 }
      );
    }

    return NextResponse.json(
      {
        success: false,
        error: "Failed to generate logo"
      },
      { status: 500 }
    );
  }
}

// GET /api/ai/generate-logo - Get generation info
export async function GET() {
  return NextResponse.json({
    service: "DALL-E 3 Logo Generator",
    status: process.env.OPENAI_API_KEY ? "configured" : "not_configured",
    message: process.env.OPENAI_API_KEY
      ? "Ready to generate logos"
      : "OpenAI API key not found. Add OPENAI_API_KEY to environment variables.",
    supportedStyles: ["modern", "minimalist", "vintage", "playful", "professional", "abstract", "geometric", "organic"],
    maxColors: 5,
  });
}
