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

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const parentId = searchParams.get('parentId');
    const includeChildren = searchParams.get('includeChildren') === 'true';

    // Build the where clause
    const whereClause: any = {
      status: 'ACTIVE'  // Use status instead of isActive for Service model
    };

    if (parentId === 'none' || parentId === '') {
      // Get only root services (no parent)
      whereClause.parentId = null;
    } else if (parentId) {
      // Get children of specific parent
      whereClause.parentId = parentId;
    } else {
      // Default behavior: if includeChildren is true, get root services, otherwise get root services
      // This ensures we get parent services that can have children
      whereClause.parentId = null;
    }

    // Fetch services using the Service model (same as admin panel)
    let services = await db.service.findMany({
      where: whereClause,
      orderBy: [
        { position: 'asc' }, // Use position field for ordering
        { updatedAt: 'desc' },
        { createdAt: 'asc' }
      ],
      include: includeChildren ? {
        children: {
          where: { status: 'ACTIVE' },
          orderBy: [
            { position: 'asc' }, // Use position field for children ordering
            { updatedAt: 'desc' },
            { createdAt: 'asc' }
          ]
        }
      } : undefined
    });

    // Auto-fix: Update child services to have INTERNAL link type if they're incorrectly set to SUBMENU
    if (!parentId) {
      // Only for root services fetch, auto-fix child services
      const childServicesToUpdate = services.filter(service => 
        service.parentId && service.linkType === 'SUBMENU'
      );
      
      if (childServicesToUpdate.length > 0) {
        console.log(`Auto-fixing ${childServicesToUpdate.length} child services from SUBMENU to INTERNAL`);
        await Promise.all(
          childServicesToUpdate.map(child => 
            db.service.update({
              where: { id: child.id },
              data: { linkType: 'INTERNAL' }
            })
          )
        );
        
        // Refetch after update
        services = await db.service.findMany({
          where: whereClause,
          orderBy: [
            { position: 'asc' }, // Use position field for ordering
            { updatedAt: 'desc' },
            { createdAt: 'asc' }
          ],
          include: includeChildren ? {
            children: {
              where: { status: 'ACTIVE' },
              orderBy: [
                { position: 'asc' }, // Use position field for children ordering
                { updatedAt: 'desc' },
                { createdAt: 'asc' }
              ]
            }
          } : undefined
        });
      }
    } else if (parentId) {
      // For specific parentId fetch, auto-fix this specific parent's children
      const childServicesToUpdate = services.filter(service => 
        service.linkType === 'SUBMENU'
      );
      
      if (childServicesToUpdate.length > 0) {
        console.log(`Auto-fixing ${childServicesToUpdate.length} child services for parent ${parentId} from SUBMENU to INTERNAL`);
        await Promise.all(
          childServicesToUpdate.map(child => 
            db.service.update({
              where: { id: child.id },
              data: { linkType: 'INTERNAL' }
            })
          )
        );
        
        // Refetch after update
        services = await db.service.findMany({
          where: whereClause,
          orderBy: [
            { position: 'asc' }, // Use position field for ordering
            { updatedAt: 'desc' },
            { createdAt: 'asc' }
          ]
        });
      }
    }

    // Transform Service data to match ServiceLink interface for backward compatibility
    const transformedServices = services.map(service => {
      const transformedService: any = {
        id: service.id,
        title: service.title,
        subtitle: null, // Service model doesn't have subtitle
        description: service.description,
        linkType: service.linkType,
        linkUrl: service.linkUrl,
        linkPage: service.linkUrl, // Use linkUrl as linkPage for internal links
        iconFile: service.iconUrl, // Use iconUrl as iconFile
        iconUrl: service.iconUrl,
        order: service.position, // Use actual position from database
        isActive: service.status === 'ACTIVE',
        parentId: service.parentId,
        createdAt: service.createdAt,
        updatedAt: service.updatedAt
      };

      // Include children if they exist
      if (service.children && service.children.length > 0) {
        transformedService.children = service.children.map(child => ({
          id: child.id,
          title: child.title,
          subtitle: null,
          description: child.description,
          linkType: child.linkType,
          linkUrl: child.linkUrl,
          linkPage: child.linkUrl,
          iconFile: child.iconUrl,
          iconUrl: child.iconUrl,
          order: child.position, // Use actual position from database
          isActive: child.status === 'ACTIVE',
          parentId: child.parentId,
          createdAt: child.createdAt,
          updatedAt: child.updatedAt
        }));
      }

      return transformedService;
    });

    return NextResponse.json({
      success: true,
      data: transformedServices,
      count: transformedServices.length
    });

  } catch (error) {
    console.error('Error fetching service links:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: 'Failed to fetch service links',
        message: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    );
  }
}

export async function PUT(request: NextRequest) {
  try {
    const body = await request.json();
    const { id } = body;
    
    if (!id) {
      return NextResponse.json(
        { 
          success: false, 
          error: 'Service ID is required' 
        },
        { status: 400 }
      );
    }

    // Update the service using Service model
    const updatedService = await db.service.update({
      where: { id },
      data: {
        ...body,
        status: body.isActive !== undefined ? (body.isActive ? 'ACTIVE' : 'INACTIVE') : undefined
      }
    });

    // Transform back to ServiceLink interface for consistency
    const transformedService = {
      id: updatedService.id,
      title: updatedService.title,
      subtitle: null,
      description: updatedService.description,
      linkType: updatedService.linkType,
      linkUrl: updatedService.linkUrl,
      linkPage: updatedService.linkUrl,
      iconFile: updatedService.iconUrl,
      iconUrl: updatedService.iconUrl,
      order: service.position, // Use actual position from database
      isActive: updatedService.status === 'ACTIVE',
      parentId: updatedService.parentId,
      createdAt: updatedService.createdAt,
      updatedAt: updatedService.updatedAt
    };

    return NextResponse.json({
      success: true,
      data: transformedService,
      message: 'Service link updated successfully'
    });

  } catch (error) {
    console.error('Error updating service link:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: 'Failed to update service link',
        message: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const {
      title,
      subtitle,
      description,
      linkType,
      linkUrl,
      linkPage,
      iconFile,
      iconUrl,
      order,
      isActive = true,
      parentId
    } = body;

    // Validate required fields
    if (!title || !linkType) {
      return NextResponse.json(
        { 
          success: false, 
          error: 'Title and link type are required' 
        },
        { status: 400 }
      );
    }

    // Validate link type specific fields
    if (linkType === 'EXTERNAL' && !linkUrl) {
      return NextResponse.json(
        { 
          success: false, 
          error: 'External link URL is required for EXTERNAL link type' 
        },
        { status: 400 }
      );
    }

    if (linkType === 'INTERNAL' && !linkPage) {
      return NextResponse.json(
        { 
          success: false, 
          error: 'Internal page is required for INTERNAL link type' 
        },
        { status: 400 }
      );
    }

    // Handle parentId - convert 'none' to null
    const finalParentId = parentId === 'none' || parentId === '' ? null : parentId;

    // Generate slug from title
    const slug = title
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/(^-|-$)/g, '');

    const serviceLink = await db.service.create({
      data: {
        title,
        slug,
        description: description || '',
        linkType,
        linkUrl: linkUrl || linkPage, // Use linkUrl or linkPage
        iconUrl: iconUrl || iconFile, // Use iconUrl or iconFile
        status: isActive ? 'ACTIVE' : 'INACTIVE',
        parentId: finalParentId,
        category: 'lainnya', // Default category
        estimatedTime: '', // Default empty
        requirements: [], // Default empty array
        isNewTab: false // Default false
      }
    });

    // Transform back to ServiceLink interface for consistency
    const transformedService = {
      id: serviceLink.id,
      title: serviceLink.title,
      subtitle: null,
      description: serviceLink.description,
      linkType: serviceLink.linkType,
      linkUrl: serviceLink.linkUrl,
      linkPage: serviceLink.linkUrl,
      iconFile: serviceLink.iconUrl,
      iconUrl: serviceLink.iconUrl,
      order: service.position, // Use actual position from database
      isActive: serviceLink.status === 'ACTIVE',
      parentId: serviceLink.parentId,
      createdAt: serviceLink.createdAt,
      updatedAt: serviceLink.updatedAt
    };

    return NextResponse.json({
      success: true,
      data: transformedService,
      message: 'Service link created successfully'
    });

  } catch (error) {
    console.error('Error creating service link:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: 'Failed to create service link',
        message: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    );
  }
}