import { NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';
import { requireAdminAuth } from '@/lib/auth';
import { getLocalizedValue } from '@/lib/i18n';

const prisma = new PrismaClient();

// GET /api/news - Public endpoint to fetch news
export async function GET(request: Request) {
    try {
        const { searchParams } = new URL(request.url);
        const limit = parseInt(searchParams.get('limit') || '10');
        const featuredOnly = searchParams.get('featured') === 'true';
        const locale = searchParams.get('locale');

        const where = featuredOnly ? { featured: true } : {};

        const news = await prisma.news.findMany({
            where,
            orderBy: { publishedAt: 'desc' },
            take: limit,
            include: {
                special: {
                    select: {
                        id: true,
                        name: true
                    }
                }
            }
        });

        if (locale) {
            const localizedNews = news.map(item => ({
                ...item,
                title: getLocalizedValue(item.title, locale),
                content: getLocalizedValue(item.content, locale),
                special: item.special ? {
                    ...item.special,
                    name: getLocalizedValue(item.special.name, locale)
                } : null
            }));
            return NextResponse.json(localizedNews);
        }

        return NextResponse.json(news);
    } catch (error) {
        console.error('Error fetching news:', error);
        return NextResponse.json({ error: 'Failed to fetch news' }, { status: 500 });
    }
}

// POST /api/news - Create news (requires auth)
export async function POST(request: Request) {
    const authError = await requireAdminAuth(request as any);
    if (authError) {
        return authError;
    }

    try {
        const body = await request.json();
        const { title, content, author, featured, specialId } = body;

        if (!title || !content) {
            return NextResponse.json(
                { error: 'Title and content are required' },
                { status: 400 }
            );
        }

        // Ensure title and content are stored as JSON
        const titleData = typeof title === 'string' ? { de: title, en: title } : title;
        const contentData = typeof content === 'string' ? { de: content, en: content } : content;

        const news = await prisma.news.create({
            data: {
                title: titleData,
                content: contentData,
                author: author || null,
                featured: featured || false,
                specialId: specialId || null
            },
            include: {
                special: {
                    select: {
                        id: true,
                        name: true
                    }
                }
            }
        });

        return NextResponse.json(news, { status: 201 });
    } catch (error) {
        console.error('Error creating news:', error);
        return NextResponse.json({ error: 'Failed to create news' }, { status: 500 });
    }
}

// PUT /api/news - Update news (requires auth)
export async function PUT(request: Request) {
    const authError = await requireAdminAuth(request as any);
    if (authError) {
        return authError;
    }

    try {
        const body = await request.json();
        const { id, title, content, author, featured, specialId } = body;

        if (!id) {
            return NextResponse.json({ error: 'News ID is required' }, { status: 400 });
        }

        const updateData: any = {};
        if (title !== undefined) updateData.title = typeof title === 'string' ? { de: title, en: title } : title;
        if (content !== undefined) updateData.content = typeof content === 'string' ? { de: content, en: content } : content;
        if (author !== undefined) updateData.author = author || null;
        if (featured !== undefined) updateData.featured = featured;
        if (specialId !== undefined) updateData.specialId = specialId || null;

        const news = await prisma.news.update({
            where: { id },
            data: updateData,
            include: {
                special: {
                    select: {
                        id: true,
                        name: true
                    }
                }
            }
        });

        return NextResponse.json(news);
    } catch (error) {
        console.error('Error updating news:', error);
        return NextResponse.json({ error: 'Failed to update news' }, { status: 500 });
    }
}

// DELETE /api/news - Delete news (requires auth)
export async function DELETE(request: Request) {
    const authError = await requireAdminAuth(request as any);
    if (authError) {
        return authError;
    }

    try {
        const body = await request.json();
        const { id } = body;

        if (!id) {
            return NextResponse.json({ error: 'News ID is required' }, { status: 400 });
        }

        await prisma.news.delete({
            where: { id }
        });

        return NextResponse.json({ success: true });
    } catch (error) {
        console.error('Error deleting news:', error);
        return NextResponse.json({ error: 'Failed to delete news' }, { status: 500 });
    }
}
