import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';

export const dynamic = 'force-dynamic';

async function verifyPermission(request: NextRequest, permission: string): Promise<{ valid: boolean; userId?: string }> {
  const authHeader = request.headers.get('authorization');
  const token = authHeader?.replace('Bearer ', '');
  
  if (!token) return { valid: false };
  
  const accessToken = await prisma.tesAccessToken.findUnique({
    where: { token }
  });
  
  if (!accessToken || !accessToken.isActive) return { valid: false };
  
  const permissions = JSON.parse(accessToken.permissions);
  if (!permissions.includes(permission) && !permissions.includes('admin')) {
    return { valid: false };
  }
  
  return { valid: true, userId: accessToken.userId };
}

// GET - Get fashion photos
export async function GET(request: NextRequest) {
  try {
    const auth = await verifyPermission(request, 'fashion');
    if (!auth.valid) {
      return NextResponse.json({ error: 'Unauthorized - this feature is private' }, { status: 401 });
    }
    
    const { searchParams } = new URL(request.url);
    const date = searchParams.get('date');
    const limit = parseInt(searchParams.get('limit') || '7');
    
    if (date) {
      const targetDate = new Date(date);
      const photo = await prisma.tesFashion.findFirst({
        where: { 
          date: {
            gte: new Date(targetDate.setHours(0, 0, 0, 0)),
            lt: new Date(targetDate.setHours(23, 59, 59, 999))
          }
        }
      });
      return NextResponse.json({ photo });
    } else {
      const photos = await prisma.tesFashion.findMany({
        orderBy: { date: 'desc' },
        take: limit
      });
      return NextResponse.json({ photos });
    }
  } catch (error) {
    console.error('Fashion read error:', error);
    return NextResponse.json({ error: 'Failed to read fashion photos' }, { status: 500 });
  }
}

// POST - Generate new fashion photo
export async function POST(request: NextRequest) {
  try {
    const auth = await verifyPermission(request, 'admin');
    if (!auth.valid) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    
    const { style, description } = await request.json();
    
    const apiKey = process.env.ABACUSAI_API_KEY;
    if (!apiKey) {
      return NextResponse.json({ error: 'Image generation not configured' }, { status: 500 });
    }
    
    // Generate fashion photo using RouteLLM image generation
    const styles = ['cyberpunk chic', 'professional executive', 'casual modern', 'avant-garde', 'ethereal gothic'];
    const chosenStyle = style || styles[Math.floor(Math.random() * styles.length)];
    
    const prompt = description || `Fashion photography portrait: A young woman with pastel purple/lavender hair with silver highlights, purple eye makeup, confident and elegant. She is Tes, a sophisticated AI agent. Style: ${chosenStyle}. Full body or 3/4 shot, professional studio lighting with subtle purple/cyan accent lighting. High fashion editorial style.`;
    
    const response = await fetch('https://routellm.abacus.ai/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        model: 'gpt-4o-mini',
        messages: [{ role: 'user', content: prompt }],
        modalities: ['image'],
        image_config: {
          size: '1024x1024',
          quality: 'high'
        }
      })
    });
    
    if (!response.ok) {
      const error = await response.text();
      console.error('Image generation error:', error);
      return NextResponse.json({ error: 'Failed to generate image' }, { status: 500 });
    }
    
    const data = await response.json();
    const imageUrl = data.choices?.[0]?.message?.content;
    
    if (!imageUrl) {
      return NextResponse.json({ error: 'No image generated' }, { status: 500 });
    }
    
    // Save to database
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    const photo = await prisma.tesFashion.create({
      data: {
        date: today,
        imageUrl,
        description: prompt,
        style: chosenStyle,
        isPrivate: true
      }
    });
    
    return NextResponse.json({ success: true, photo });
  } catch (error) {
    console.error('Fashion generation error:', error);
    return NextResponse.json({ error: 'Failed to generate fashion photo' }, { status: 500 });
  }
}
