
-- Chart of Accounts
CREATE TABLE public.chart_of_accounts (
  id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  association_id UUID REFERENCES public.associations(id) ON DELETE CASCADE NOT NULL,
  account_number TEXT NOT NULL,
  account_name TEXT NOT NULL,
  account_type TEXT NOT NULL DEFAULT 'expense',
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

ALTER TABLE public.chart_of_accounts ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Authenticated users can view chart_of_accounts"
  ON public.chart_of_accounts FOR SELECT TO authenticated USING (true);

CREATE POLICY "Authenticated users can insert chart_of_accounts"
  ON public.chart_of_accounts FOR INSERT TO authenticated WITH CHECK (true);

CREATE POLICY "Authenticated users can update chart_of_accounts"
  ON public.chart_of_accounts FOR UPDATE TO authenticated USING (true) WITH CHECK (true);

CREATE POLICY "Authenticated users can delete chart_of_accounts"
  ON public.chart_of_accounts FOR DELETE TO authenticated USING (true);

-- Journal Entries
CREATE TABLE public.journal_entries (
  id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  association_id UUID REFERENCES public.associations(id) ON DELETE CASCADE NOT NULL,
  chart_of_account_id UUID REFERENCES public.chart_of_accounts(id) ON DELETE SET NULL,
  date DATE NOT NULL DEFAULT CURRENT_DATE,
  description TEXT,
  amount NUMERIC(12,2) NOT NULL DEFAULT 0,
  type TEXT NOT NULL DEFAULT 'debit' CHECK (type IN ('debit', 'credit')),
  created_by UUID,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

ALTER TABLE public.journal_entries ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Authenticated users can view journal_entries"
  ON public.journal_entries FOR SELECT TO authenticated USING (true);

CREATE POLICY "Authenticated users can insert journal_entries"
  ON public.journal_entries FOR INSERT TO authenticated WITH CHECK (true);

CREATE POLICY "Authenticated users can update journal_entries"
  ON public.journal_entries FOR UPDATE TO authenticated USING (true) WITH CHECK (true);

CREATE POLICY "Authenticated users can delete journal_entries"
  ON public.journal_entries FOR DELETE TO authenticated USING (true);
