-- 1. Add accounting_system column
ALTER TABLE public.chart_of_accounts
  ADD COLUMN IF NOT EXISTS accounting_system text NOT NULL DEFAULT 'buildium';

-- 2. Constrain values
ALTER TABLE public.chart_of_accounts
  DROP CONSTRAINT IF EXISTS chart_of_accounts_accounting_system_check;
ALTER TABLE public.chart_of_accounts
  ADD CONSTRAINT chart_of_accounts_accounting_system_check
  CHECK (accounting_system IN ('buildium', 'zoho'));

-- 3. Tag all existing rows as buildium (already default, but explicit)
UPDATE public.chart_of_accounts
  SET accounting_system = 'buildium'
  WHERE accounting_system IS NULL OR accounting_system = '';

-- 4. Index for filtering
CREATE INDEX IF NOT EXISTS idx_chart_of_accounts_system
  ON public.chart_of_accounts(accounting_system, account_number);

-- 5. Helper: infer accounting system for an association
CREATE OR REPLACE FUNCTION public.get_association_accounting_system(_association_id uuid)
RETURNS text
LANGUAGE sql
STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
  SELECT CASE
    WHEN _association_id IS NULL THEN 'buildium'
    WHEN EXISTS (
      SELECT 1 FROM public.associations a
      WHERE a.id = _association_id
        AND a.zoho_organization_id IS NOT NULL
        AND a.zoho_organization_id <> ''
    ) THEN 'zoho'
    WHEN EXISTS (
      SELECT 1 FROM public.buildium_gl_mappings bgm
      WHERE bgm.association_id = _association_id
    ) THEN 'buildium'
    ELSE 'buildium'
  END;
$$;