/**
 * File: route.ts
 * Created by: AI Assistant
 * Date: 2025-11-29
 * Purpose: Video API endpoints with authentication and role-based access
 * 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: Request) {
  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);

    let whereClause: any = {
      OR: [
        { isPublic: true },
      ],
    };

    // Add user's own videos and class videos
    if (userProfile.role.name !== 'UMUM') {
      whereClause.OR.push(
        { uploaderId: userProfile.id }
      );
    }

    // If user is educator or admin, show videos from their classes
    if (userProfile.role.name === 'PENDIDIK' || userProfile.role.name === 'ADMIN') {
      const userClasses = await prisma.class.findMany({
        where: {
          educatorId: userProfile.id,
          isActive: true,
        },
        include: {
          videos: true,
        },
      });

      const classVideoIds = userClasses.flatMap(cls => cls.videos.map(v => v.id));
      if (classVideoIds.length > 0) {
        whereClause.OR.push({ id: { in: classVideoIds } });
      }
    }

    // If user is student, show videos from their enrolled classes
    if (userProfile.role.name === 'CALON_PENDIDIK') {
      const enrolledClasses = await prisma.classMember.findMany({
        where: {
          studentId: userProfile.id,
        },
        include: {
          class: {
            include: {
              videos: true,
            },
          },
        },
      });

      const classVideoIds = enrolledClasses.flatMap(cm => cm.class.videos.map(v => v.id));
      if (classVideoIds.length > 0) {
        whereClause.OR.push({ id: { in: classVideoIds } });
      }
    }

    const videos = await prisma.video.findMany({
      where: whereClause,
      include: {
        uploader: {
          include: {
            user: {
              select: {
                name: true,
                image: true,
              },
            },
          },
        },
      },
      orderBy: {
        createdAt: 'desc',
      },
    });

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

export async function POST(request: Request) {
  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 body = await request.json();
    const { title, description, videoUrl, videoType, isPublic } = body;

    // Validation
    if (!title || !videoUrl) {
      return NextResponse.json(
        { success: false, message: 'Title and Video URL are required' },
        { status: 400 }
      );
    }

    const video = await prisma.video.create({
      data: {
        title: title,
        description: description,
        videoUrl: videoUrl,
        videoType: videoType,
        isPublic: isPublic,
        uploaderId: userProfile.id,
        createdBy: userProfile.id,
        updatedBy: userProfile.id,
      },
    });

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