import { createAdminClient } from '@/lib/supabase/admin'

const now = () => new Date().toISOString()

export async function deactivateEmployee(id: string, note?: string): Promise<void> {
  const admin = createAdminClient()
  const { error } = await admin.from('consultants').update({
    status:         'inactive',
    is_active:      false,
    deactivated_at: now(),
    lifecycle_note: note ?? null,
  }).eq('id', id)
  if (error) throw new Error(error.message)
}

export async function markLeftDepartment(id: string, note?: string): Promise<void> {
  const admin = createAdminClient()
  const { error } = await admin.from('consultants').update({
    status:              'left_department',
    is_active:           false,
    left_department_at:  now(),
    lifecycle_note:      note ?? null,
  }).eq('id', id)
  if (error) throw new Error(error.message)
}

export async function markLeftCompany(id: string, note?: string): Promise<void> {
  const admin = createAdminClient()
  const { error } = await admin.from('consultants').update({
    status:          'left_company',
    is_active:       false,
    left_company_at: now(),
    lifecycle_note:  note ?? null,
  }).eq('id', id)
  if (error) throw new Error(error.message)
}

export async function archiveEmployee(id: string, note?: string): Promise<void> {
  const admin = createAdminClient()
  const { error } = await admin.from('consultants').update({
    status:         'archived',
    is_active:      false,
    is_archived:    true,
    archived_at:    now(),
    lifecycle_note: note ?? null,
  }).eq('id', id)
  if (error) throw new Error(error.message)
}

export async function reactivateEmployee(id: string): Promise<void> {
  const admin = createAdminClient()
  const { error } = await admin.from('consultants').update({
    status:              'active',
    is_active:           true,
    is_archived:         false,
    deactivated_at:      null,
    archived_at:         null,
    left_department_at:  null,
    left_company_at:     null,
    lifecycle_note:      null,
  }).eq('id', id)
  if (error) throw new Error(error.message)
}
