/**
 * File: route.ts
 * Created by: AI Assistant
 * Date: 2025-11-29
 * Purpose: Video API endpoints for single video operations
 * Part of: kreatiVortex - Platform Pembelajaran Tari Online
 */

import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { auth } from '@/lib/auth';
import { headers } from 'next/headers';
import { getOrCreateUserProfile } from '@/lib/profile';

export async function GET(
  _: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const video = await prisma.video.findUnique({
      where: { id },
      include: {
        uploader: {
          include: {
            user: {
              select: {
                name: true,
                image: true,
              },
            },
          },
        },
        comments: {
          include: {
            author: {
              include: {
                user: {
                  select: {
                    name: true,
                    image: true,
                  },
                },
              },
            },
          },
          orderBy: {
            createdAt: 'desc',
          },
        },
      },
    });

    if (!video) {
      return NextResponse.json(
        { success: false, message: 'Video not found' },
        { status: 404 }
      );
    }

    // Increment view count
    await prisma.video.update({
      where: { id },
      data: { viewCount: { increment: 1 } },
    });

    return NextResponse.json({ success: true, data: video });
  } catch (error) {
    console.error('Error fetching video:', error);
    return NextResponse.json(
      { success: false, message: 'Failed to fetch video' },
      { status: 500 }
    );
  }
}

export async function PUT(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const body = await request.json();
    const { title, description, videoUrl, videoType, isPublic } = body;

    const video = await prisma.video.update({
      where: { id },
      data: {
        title,
        description,
        videoUrl,
        videoType,
        isPublic,
      },
    });

    return NextResponse.json({ success: true, data: video });
  } catch (error) {
    console.error('Error updating video:', error);
    return NextResponse.json(
      { success: false, message: 'Failed to update video' },
      { status: 500 }
    );
  }
}

export async function DELETE(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await auth.api.getSession({
      headers: await headers()
    });

    if (!session?.user) {
      return NextResponse.json(
        { success: false, message: 'Unauthorized' },
        { status: 401 }
      );
    }

    // Get or create user profile
    const userProfile = await getOrCreateUserProfile(session.user.id);

    const { id } = await params;

    // Check if video exists
    const video = await prisma.video.findUnique({
      where: { id },
    });

    if (!video) {
      return NextResponse.json(
        { success: false, message: 'Video not found' },
        { status: 404 }
      );
    }

    // Check if user can delete this video
    const canDelete = userProfile.role.name === 'ADMIN' || video.uploaderId === userProfile.id;

    if (!canDelete) {
      return NextResponse.json(
        { success: false, message: 'Access denied' },
        { status: 403 }
      );
    }

    // Delete the video
    await prisma.video.delete({
      where: { id },
    });

    return NextResponse.json({ 
      success: true, 
      message: 'Video deleted successfully' 
    });

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