ALTER TABLE public.daily_cash_closings
  ADD COLUMN IF NOT EXISTS shift text NOT NULL DEFAULT 'full_day',
  ADD COLUMN IF NOT EXISTS cashier_id uuid;

-- Drop old unique if it exists (branch_id, closing_date)
DO $$
DECLARE c text;
BEGIN
  SELECT conname INTO c FROM pg_constraint
   WHERE conrelid = 'public.daily_cash_closings'::regclass
     AND contype = 'u'
     AND pg_get_constraintdef(oid) ILIKE '%(branch_id, closing_date)%';
  IF c IS NOT NULL THEN
    EXECUTE format('ALTER TABLE public.daily_cash_closings DROP CONSTRAINT %I', c);
  END IF;
END $$;

CREATE UNIQUE INDEX IF NOT EXISTS daily_cash_closings_unique_shift
  ON public.daily_cash_closings (
    closing_date,
    COALESCE(branch_id, '00000000-0000-0000-0000-000000000000'::uuid),
    COALESCE(cashier_id, '00000000-0000-0000-0000-000000000000'::uuid),
    shift
  );

CREATE INDEX IF NOT EXISTS daily_cash_closings_cashier_idx
  ON public.daily_cash_closings (cashier_id);
