// app/api/admin/update-video/route.ts
import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth-options';
import { prisma } from '@/lib/prisma';
import { writeFile, mkdir } from 'fs/promises';
import { join } from 'path';

export async function PATCH(req: Request) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.email) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const role = (session as any)?.user?.role ?? null;
    if (!(role === 'admin' || role === 'superadmin')) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    const { videoId, title } = await req.json();

    if (!videoId) {
      return NextResponse.json(
        { error: 'videoId required' },
        { status: 400 }
      );
    }

    if (!title || typeof title !== 'string' || title.trim().length === 0) {
      return NextResponse.json(
        { error: 'title required and must be non-empty' },
        { status: 400 }
      );
    }

    const updatedVideo = await prisma.video.update({
      where: { id: videoId },
      data: { title: title.trim() },
    });

    return NextResponse.json(updatedVideo, { status: 200 });
  } catch (err: any) {
    console.error('update video error', err);
    return NextResponse.json(
      { error: err?.message ?? 'server error' },
      { status: 500 }
    );
  }
}

export async function POST(req: Request) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.email)
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const role = (session as any)?.user?.role ?? null;
    if (!(role === 'admin' || role === 'superadmin')) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    const formData = await req.formData().catch(() => null);
    if (!formData) {
      return NextResponse.json({ error: 'Invalid form data' }, { status: 400 });
    }

    const videoId = formData.get('videoId') as string;
    const title = formData.get('title') as string;
    const description = formData.get('description') as string | null;
    const thumbnail = formData.get('thumbnail') as File | null;
    const restricted = formData.get('restrictedCourseIds') as string | null;

    if (!videoId)
      return NextResponse.json({ error: 'videoId required' }, { status: 400 });

    // Build update data
    const updateData: any = {};
    if (title) updateData.title = title;
    if (description !== null) updateData.description = description;

    let restrictedCourseIds: string[] | null = null;
    if (restricted) {
      try {
        const parsed = JSON.parse(restricted);
        if (Array.isArray(parsed)) {
          restrictedCourseIds = parsed.filter((id) => typeof id === 'string' && id);
        }
      } catch (err) {
        console.warn('Invalid restrictedCourseIds payload', err);
      }
    }

    // Handle thumbnail upload if provided
    if (thumbnail && thumbnail.size > 0) {
      const bytes = await thumbnail.arrayBuffer();
      const buffer = Buffer.from(bytes);

      // Save to public/thumbnails
      const uploadDir = join(process.cwd(), 'public', 'thumbnails');
      await mkdir(uploadDir, { recursive: true });

      const filename = `${videoId}-${Date.now()}.${thumbnail.type.split('/')[1] || 'jpg'}`;
      const filepath = join(uploadDir, filename);
      await writeFile(filepath, buffer);

      updateData.thumbnail = `/thumbnails/${filename}`;
    }

    if (Object.keys(updateData).length === 0 && !thumbnail && restrictedCourseIds === null) {
      return NextResponse.json({ error: 'No fields to update' }, { status: 400 });
    }

    const updated = await prisma.video.update({
      where: { id: videoId },
      data: updateData,
    });

    if (restrictedCourseIds !== null) {
      await prisma.videoCourse.deleteMany({ where: { videoId } });
      if (restrictedCourseIds.length > 0) {
        await prisma.videoCourse.createMany({
          data: restrictedCourseIds.map((courseId) => ({
            videoId,
            courseId,
            exclusive: true,
          })),
          skipDuplicates: true,
        });
      }
    }

    return NextResponse.json({ success: true, video: updated });
  } catch (err: any) {
    console.error('update video error', err);
    return NextResponse.json(
      { error: err?.message ?? 'server error' },
      { status: 500 }
    );
  }
}
