'use server'

import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'
import { createClient } from '@/lib/supabase/server'
import { getAppOrg } from '@/lib/org'
import { getEffectiveUser } from '@/lib/effective-user'
import { canTransfer } from '@/lib/permissions'

function fail(msg: string): never {
  redirect(`/tools/cc-expenses/rules?error=${encodeURIComponent(msg)}`)
}
function ok(msg: string): never {
  redirect(`/tools/cc-expenses/rules?info=${encodeURIComponent(msg)}`)
}

// ============================================================
// Highlight keywords — create + delete (no edit; tiny rows)
// ============================================================

export async function createHighlightKeyword(formData: FormData) {
  const keyword = String(formData.get('keyword') ?? '').trim()
  if (!keyword) fail('Keyword is required.')

  const supabase = await createClient()
  const org = await getAppOrg(supabase)
  if (!org) fail('Organization not found.')

  const eu = await getEffectiveUser(supabase, org.id)
  if (!canTransfer(eu)) fail('Only an owner can manage rules.')

  const { error } = await supabase
    .from('cc_highlight_keywords')
    .insert({ org_id: org.id, keyword })
  if (error) {
    if (error.code === '23505') {
      fail(`"${keyword}" is already a highlight keyword.`)
    }
    fail(error.message)
  }
  revalidatePath('/tools/cc-expenses/rules')
  ok(`Added highlight keyword "${keyword}".`)
}

export async function deleteHighlightKeyword(formData: FormData) {
  const id = String(formData.get('id') ?? '').trim()
  if (!id) fail('Missing id.')

  const supabase = await createClient()
  const org = await getAppOrg(supabase)
  if (!org) fail('Organization not found.')

  const eu = await getEffectiveUser(supabase, org.id)
  if (!canTransfer(eu)) fail('Only an owner can manage rules.')

  const { error } = await supabase
    .from('cc_highlight_keywords')
    .delete()
    .eq('id', id)
    .eq('org_id', org.id)
  if (error) fail(error.message)
  revalidatePath('/tools/cc-expenses/rules')
}

// ============================================================
// Auto-assign rules — create + update + delete
// ============================================================

export async function createAutoRule(formData: FormData) {
  const keyword = String(formData.get('keyword') ?? '').trim()
  const projectId = String(formData.get('project_id') ?? '').trim()
  const assignmentDescription =
    String(formData.get('assignment_description') ?? '').trim() || null
  const category = String(formData.get('category') ?? '').trim() || null

  if (!keyword) fail('Keyword is required.')
  if (!projectId) fail('Pick a project.')

  const supabase = await createClient()
  const org = await getAppOrg(supabase)
  if (!org) fail('Organization not found.')

  const eu = await getEffectiveUser(supabase, org.id)
  if (!canTransfer(eu)) fail('Only an owner can manage rules.')

  // Validate the project belongs to this org.
  const { data: project } = await supabase
    .from('projects')
    .select('id')
    .eq('id', projectId)
    .eq('org_id', org.id)
    .maybeSingle<{ id: string }>()
  if (!project) fail('Selected project not found in this org.')

  const { error } = await supabase.from('cc_auto_rules').insert({
    org_id: org.id,
    keyword,
    project_id: projectId,
    assignment_description: assignmentDescription,
    category,
  })
  if (error) {
    if (error.code === '23505') {
      fail(`A rule for "${keyword}" already exists.`)
    }
    fail(error.message)
  }
  revalidatePath('/tools/cc-expenses/rules')
  ok(`Added auto-assign rule for "${keyword}".`)
}

export async function updateAutoRule(formData: FormData) {
  const id = String(formData.get('id') ?? '').trim()
  if (!id) fail('Missing rule id.')
  const keyword = String(formData.get('keyword') ?? '').trim()
  const projectId = String(formData.get('project_id') ?? '').trim()
  const assignmentDescription =
    String(formData.get('assignment_description') ?? '').trim() || null
  const category = String(formData.get('category') ?? '').trim() || null

  if (!keyword) fail('Keyword is required.')
  if (!projectId) fail('Pick a project.')

  const supabase = await createClient()
  const org = await getAppOrg(supabase)
  if (!org) fail('Organization not found.')

  const eu = await getEffectiveUser(supabase, org.id)
  if (!canTransfer(eu)) fail('Only an owner can manage rules.')

  const { error } = await supabase
    .from('cc_auto_rules')
    .update({
      keyword,
      project_id: projectId,
      assignment_description: assignmentDescription,
      category,
    })
    .eq('id', id)
    .eq('org_id', org.id)
  if (error) {
    if (error.code === '23505') {
      fail(`A rule for "${keyword}" already exists.`)
    }
    fail(error.message)
  }
  revalidatePath('/tools/cc-expenses/rules')
  ok(`Updated rule for "${keyword}".`)
}

export async function deleteAutoRule(formData: FormData) {
  const id = String(formData.get('id') ?? '').trim()
  if (!id) fail('Missing rule id.')

  const supabase = await createClient()
  const org = await getAppOrg(supabase)
  if (!org) fail('Organization not found.')

  const eu = await getEffectiveUser(supabase, org.id)
  if (!canTransfer(eu)) fail('Only an owner can manage rules.')

  const { error } = await supabase
    .from('cc_auto_rules')
    .delete()
    .eq('id', id)
    .eq('org_id', org.id)
  if (error) fail(error.message)
  revalidatePath('/tools/cc-expenses/rules')
}
