
-- Add columns to chart_of_accounts
ALTER TABLE chart_of_accounts ADD COLUMN IF NOT EXISTS parent_account_id uuid REFERENCES chart_of_accounts(id);
ALTER TABLE chart_of_accounts ADD COLUMN IF NOT EXISTS is_active boolean NOT NULL DEFAULT true;
ALTER TABLE chart_of_accounts ADD COLUMN IF NOT EXISTS description text;

-- Add account_category to bank_accounts
ALTER TABLE bank_accounts ADD COLUMN IF NOT EXISTS account_category text NOT NULL DEFAULT 'operating';

-- Create vendors table
CREATE TABLE IF NOT EXISTS vendors (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  association_id uuid NOT NULL REFERENCES associations(id) ON DELETE CASCADE,
  name text NOT NULL,
  contact_name text,
  email text,
  phone text,
  address text,
  tax_id text,
  payment_terms text DEFAULT '30',
  default_expense_account_id uuid REFERENCES chart_of_accounts(id),
  is_active boolean NOT NULL DEFAULT true,
  notes text,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now()
);

-- Create bank_transactions table (unified register)
CREATE TABLE IF NOT EXISTS bank_transactions (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  bank_account_id uuid NOT NULL REFERENCES bank_accounts(id) ON DELETE CASCADE,
  association_id uuid NOT NULL REFERENCES associations(id) ON DELETE CASCADE,
  date date NOT NULL DEFAULT CURRENT_DATE,
  transaction_type text NOT NULL DEFAULT 'payment',
  description text,
  reference_number text,
  debit numeric NOT NULL DEFAULT 0,
  credit numeric NOT NULL DEFAULT 0,
  is_cleared boolean NOT NULL DEFAULT false,
  cleared_date date,
  reconciliation_id uuid,
  related_entity_type text,
  related_entity_id uuid,
  created_by uuid,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now()
);

-- Create owner_ledger_entries
CREATE TABLE IF NOT EXISTS owner_ledger_entries (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  association_id uuid NOT NULL REFERENCES associations(id) ON DELETE CASCADE,
  owner_id uuid NOT NULL REFERENCES owners(id) ON DELETE CASCADE,
  unit_id uuid REFERENCES units(id),
  date date NOT NULL DEFAULT CURRENT_DATE,
  transaction_type text NOT NULL,
  description text,
  debit numeric NOT NULL DEFAULT 0,
  credit numeric NOT NULL DEFAULT 0,
  reference_id uuid,
  reference_type text,
  created_by uuid,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now()
);

-- Create bills table (proper AP)
CREATE TABLE IF NOT EXISTS bills (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  association_id uuid NOT NULL REFERENCES associations(id) ON DELETE CASCADE,
  vendor_id uuid REFERENCES vendors(id),
  invoice_number text,
  bill_date date NOT NULL DEFAULT CURRENT_DATE,
  due_date date,
  amount numeric NOT NULL DEFAULT 0,
  amount_paid numeric NOT NULL DEFAULT 0,
  expense_account_id uuid REFERENCES chart_of_accounts(id),
  description text,
  status text NOT NULL DEFAULT 'draft',
  approved_by uuid,
  approved_date date,
  paid_date date,
  payment_method text,
  check_id uuid REFERENCES checks(id),
  attachment_url text,
  notes text,
  created_by uuid,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now()
);

-- Create deposit_batches
CREATE TABLE IF NOT EXISTS deposit_batches (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  association_id uuid NOT NULL REFERENCES associations(id) ON DELETE CASCADE,
  bank_account_id uuid NOT NULL REFERENCES bank_accounts(id),
  deposit_date date NOT NULL DEFAULT CURRENT_DATE,
  total_amount numeric NOT NULL DEFAULT 0,
  status text NOT NULL DEFAULT 'open',
  memo text,
  bank_transaction_id uuid,
  created_by uuid,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now()
);

-- Create deposit_batch_items
CREATE TABLE IF NOT EXISTS deposit_batch_items (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  deposit_batch_id uuid NOT NULL REFERENCES deposit_batches(id) ON DELETE CASCADE,
  owner_ledger_entry_id uuid REFERENCES owner_ledger_entries(id),
  description text,
  amount numeric NOT NULL DEFAULT 0,
  created_at timestamptz NOT NULL DEFAULT now()
);

-- Create bank_transfers
CREATE TABLE IF NOT EXISTS bank_transfers (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  association_id uuid NOT NULL REFERENCES associations(id) ON DELETE CASCADE,
  from_bank_account_id uuid NOT NULL REFERENCES bank_accounts(id),
  to_bank_account_id uuid NOT NULL REFERENCES bank_accounts(id),
  amount numeric NOT NULL,
  transfer_date date NOT NULL DEFAULT CURRENT_DATE,
  description text,
  from_transaction_id uuid,
  to_transaction_id uuid,
  created_by uuid,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now()
);

-- Create bank_reconciliations
CREATE TABLE IF NOT EXISTS bank_reconciliations (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  bank_account_id uuid NOT NULL REFERENCES bank_accounts(id),
  association_id uuid NOT NULL REFERENCES associations(id) ON DELETE CASCADE,
  statement_date date NOT NULL,
  opening_balance numeric NOT NULL DEFAULT 0,
  closing_balance numeric NOT NULL DEFAULT 0,
  cleared_balance numeric NOT NULL DEFAULT 0,
  difference numeric NOT NULL DEFAULT 0,
  status text NOT NULL DEFAULT 'in_progress',
  reconciled_by uuid,
  reconciled_at timestamptz,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now()
);

-- Add FK for bank_transactions reconciliation_id
ALTER TABLE bank_transactions 
  ADD CONSTRAINT bank_transactions_reconciliation_id_fkey 
  FOREIGN KEY (reconciliation_id) REFERENCES bank_reconciliations(id);

-- Add FK for bank_transfers transaction ids
ALTER TABLE bank_transfers 
  ADD CONSTRAINT bank_transfers_from_transaction_id_fkey 
  FOREIGN KEY (from_transaction_id) REFERENCES bank_transactions(id);
ALTER TABLE bank_transfers 
  ADD CONSTRAINT bank_transfers_to_transaction_id_fkey 
  FOREIGN KEY (to_transaction_id) REFERENCES bank_transactions(id);

-- Add FK for deposit_batches bank_transaction_id
ALTER TABLE deposit_batches 
  ADD CONSTRAINT deposit_batches_bank_transaction_id_fkey 
  FOREIGN KEY (bank_transaction_id) REFERENCES bank_transactions(id);

-- RLS for all new tables
ALTER TABLE vendors ENABLE ROW LEVEL SECURITY;
ALTER TABLE bank_transactions ENABLE ROW LEVEL SECURITY;
ALTER TABLE owner_ledger_entries ENABLE ROW LEVEL SECURITY;
ALTER TABLE bills ENABLE ROW LEVEL SECURITY;
ALTER TABLE deposit_batches ENABLE ROW LEVEL SECURITY;
ALTER TABLE deposit_batch_items ENABLE ROW LEVEL SECURITY;
ALTER TABLE bank_transfers ENABLE ROW LEVEL SECURITY;
ALTER TABLE bank_reconciliations ENABLE ROW LEVEL SECURITY;

-- Staff access policies
CREATE POLICY "Staff full access on vendors" ON vendors FOR ALL TO authenticated 
  USING (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager')) 
  WITH CHECK (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager'));

CREATE POLICY "Staff full access on bank_transactions" ON bank_transactions FOR ALL TO authenticated 
  USING (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager')) 
  WITH CHECK (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager'));

CREATE POLICY "Staff full access on owner_ledger_entries" ON owner_ledger_entries FOR ALL TO authenticated 
  USING (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager')) 
  WITH CHECK (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager'));

CREATE POLICY "Owners can view own ledger" ON owner_ledger_entries FOR SELECT TO authenticated 
  USING (EXISTS (SELECT 1 FROM owners WHERE owners.id = owner_ledger_entries.owner_id AND owners.user_id = auth.uid()));

CREATE POLICY "Staff full access on bills" ON bills FOR ALL TO authenticated 
  USING (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager')) 
  WITH CHECK (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager'));

CREATE POLICY "Staff full access on deposit_batches" ON deposit_batches FOR ALL TO authenticated 
  USING (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager')) 
  WITH CHECK (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager'));

CREATE POLICY "Staff full access on deposit_batch_items" ON deposit_batch_items FOR ALL TO authenticated 
  USING (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager')) 
  WITH CHECK (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager'));

CREATE POLICY "Staff full access on bank_transfers" ON bank_transfers FOR ALL TO authenticated 
  USING (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager')) 
  WITH CHECK (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager'));

CREATE POLICY "Staff full access on bank_reconciliations" ON bank_reconciliations FOR ALL TO authenticated 
  USING (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager')) 
  WITH CHECK (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager'));

-- Updated_at triggers for new tables
CREATE TRIGGER update_vendors_updated_at BEFORE UPDATE ON vendors FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
CREATE TRIGGER update_bank_transactions_updated_at BEFORE UPDATE ON bank_transactions FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
CREATE TRIGGER update_owner_ledger_entries_updated_at BEFORE UPDATE ON owner_ledger_entries FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
CREATE TRIGGER update_bills_updated_at BEFORE UPDATE ON bills FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
CREATE TRIGGER update_deposit_batches_updated_at BEFORE UPDATE ON deposit_batches FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
CREATE TRIGGER update_bank_transfers_updated_at BEFORE UPDATE ON bank_transfers FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
CREATE TRIGGER update_bank_reconciliations_updated_at BEFORE UPDATE ON bank_reconciliations FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
