import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs'
import { cookies } from 'next/headers'
import { NextResponse } from 'next/server'

export const dynamic = 'force-dynamic'

export async function PUT(request: Request) {
  try {
    const supabase = createRouteHandlerClient({ cookies })
    
    // Vérifier l'authentification et les droits staff
    const { data: { session } } = await supabase.auth.getSession()
    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const { data: staffUser } = await supabase
      .from('staff_users')
      .select('is_staff')
      .eq('user_id', session.user.id)
      .maybeSingle()

    if (!staffUser?.is_staff) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
    }

    const body = await request.json()
    const { org_id, old_period_label, new_period_label } = body

    if (!org_id || !old_period_label || !new_period_label) {
      return NextResponse.json(
        { error: 'Missing required fields' },
        { status: 400 }
      )
    }

    console.log('📝 Update Period - Org:', org_id, 'Old:', old_period_label, 'New:', new_period_label)

    // Mettre à jour tous les documents de cette période
    const { error, count } = await supabase
      .from('documents')
      .update({ period_label: new_period_label })
      .eq('org_id', org_id)
      .eq('period_label', old_period_label)
      .eq('category', 'docs_comptables')

    if (error) {
      console.error('❌ Error updating period:', error)
      return NextResponse.json({ error: error.message }, { status: 500 })
    }

    console.log('✅ Updated', count, 'documents')

    return NextResponse.json({ 
      success: true,
      updated_count: count
    })

  } catch (error: any) {
    console.error('❌ Update period error:', error)
    return NextResponse.json(
      { error: error.message || 'Internal server error' },
      { status: 500 }
    )
  }
}
