// src/app/api/primary-options/[id]/route.ts
import { NextRequest, NextResponse } from 'next/server';

export async function GET(
  request: NextRequest,
  { params }:  { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const response = await fetch(
      `${process.env.BACKEND_URL}/api/v1/primary-options/${id}`,
      {
        headers: {
          'Content-Type': 'application/json',
        },
      }
    );

    if (!response.ok) {
      throw new Error(`Error from backend: ${response.status}`);
    }

    const data = await response.json();
    return NextResponse.json(data);
  } catch (error) {
    console.error('Error fetching primary option:', error);
    return NextResponse.json(
      { status: 'error', message: 'Failed to fetch primary option' },
      { status: 500 }
    );
  }
}

export async function PUT(
  request: NextRequest,
  { params }:  { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const body = await request.json();

    const response = await fetch(
      `${process.env.BACKEND_URL}/api/v1/primary-options/${id}`,
      {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(body),
      }
    );

    const data = await response.json();

    if (!response.ok) {
      return NextResponse.json(
        { status: 'error', message: data.message || 'Failed to update primary option' },
        { status: response.status }
      );
    }

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



export async function DELETE(
  request: NextRequest,
  { params }:  { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  
  try {
    // ابتدا بررسی می‌کنیم که این آپشن به چند دسته‌بندی متصل است
    const checkResponse = await fetch(
      `${process.env.BACKEND_URL}/api/v1/primary-options/${id}/related-categories`,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      }
    );
    
    const { categories } = await checkResponse.json();
    
    if (categories && categories.length > 0) {
      return NextResponse.json(
        {
          status: 'warning',
          message: `This primary option is linked to ${categories.length} categories. Deleting it will remove these relationships.`,
          relatedCategories: categories,
          requireConfirmation: true
        },
        { status: 200 } 
      );
    }
    
    const deleteResponse = await fetch(
      `${process.env.BACKEND_URL}/api/v1/primary-options/${id}`,
      {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
        },
      }
    );
    
    if (!deleteResponse.ok) {
      const errorData = await deleteResponse.json();
      return NextResponse.json(
        { status: 'error', message: errorData.message || `Error deleting primary option` },
        { status: deleteResponse.status }
      );
    }
    
    return NextResponse.json(
      { status: 'success', message: 'Primary option deleted successfully' },
      { status: 200 }
    );
  } catch (error) {
    console.error(`Error in DELETE /api/v1/primary-options/${id}:`, error);
    return NextResponse.json(
      { status: 'error', message: 'Internal server error' },
      { status: 500 }
    );
  }
}

