import { supabase } from '@/integrations/supabase/client';

export const NOTICE_LEVELS = {
  FIRST: 'First Notice',
  SECOND: 'Second Notice',
  THIRD: 'Third & Final Notice'
};

export const VALID_STATUSES = ['open', 'closed', 'resolved', 'pending', 'recommended_for_fining', 'fined', 'escalated'];

export const isValidStatus = (status) => {
  return status && VALID_STATUSES.includes(status.toLowerCase());
};

export const getNoticeLevel = (count) => {
  if (count >= 3) return NOTICE_LEVELS.THIRD;
  if (count === 2) return NOTICE_LEVELS.SECOND;
  return NOTICE_LEVELS.FIRST;
};

export const getNoticeColor = (level) => {
  switch (level) {
    case NOTICE_LEVELS.THIRD:
      return 'bg-red-100 text-red-700 border-red-200';
    case NOTICE_LEVELS.SECOND:
      return 'bg-orange-100 text-orange-700 border-orange-200';
    case NOTICE_LEVELS.FIRST:
    default:
      return 'bg-blue-100 text-blue-700 border-blue-200';
  }
};

export const calculateNextNoticeLevel = async (unitId) => {
  if (!unitId) return NOTICE_LEVELS.FIRST;

  try {
    const { count, error } = await supabase
      .from('violations')
      .select('*', { count: 'exact', head: true })
      .eq('unit_id', unitId);

    if (error) throw error;
    
    return getNoticeLevel((count || 0) + 1);
  } catch (err) {
    console.error('Error calculating notice level:', err);
    return NOTICE_LEVELS.FIRST;
  }
};

export const getNoticeHistory = async (unitId) => {
  if (!unitId) return [];
  
  const { data, error } = await supabase
    .from('violations')
    .select('*')
    .eq('unit_id', unitId)
    .order('created_at', { ascending: true });

  if (error) {
    console.error('Error fetching history:', error);
    return [];
  }
  return data;
};
