-- Migration: end_customers table + RLS + orders.end_customer_id

CREATE TABLE IF NOT EXISTS end_customers (
  id            UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  partner_id    UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
  company_name  TEXT NOT NULL,
  vat_id        TEXT,
  first_name    TEXT,
  last_name     TEXT,
  street        TEXT,
  zip           TEXT,
  city          TEXT,
  is_anonymized BOOLEAN NOT NULL DEFAULT false,
  created_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);

ALTER TABLE end_customers ENABLE ROW LEVEL SECURITY;

DROP POLICY IF EXISTS "Partner sehen nur eigene Endkunden" ON end_customers;

CREATE POLICY "Partner sehen nur eigene Endkunden"
ON end_customers FOR ALL
USING (auth.uid() = partner_id)
WITH CHECK (auth.uid() = partner_id);

ALTER TABLE orders
  ADD COLUMN IF NOT EXISTS end_customer_id UUID REFERENCES end_customers(id) ON DELETE SET NULL;
