-- MIGRATION SCRIPT
-- Run this to update your existing tables with the new columns

-- 1. Add 'ean' to inventory (This was the error you saw)
alter table public.inventory add column if not exists ean text;

-- 2. Add 'user_id' to all key tables (For the authentication fix I made)
alter table public.inventory add column if not exists user_id uuid references auth.users;
alter table public.suppliers add column if not exists user_id uuid references auth.users;
alter table public.customers add column if not exists user_id uuid references auth.users;
alter table public.orders add column if not exists user_id uuid references auth.users;
alter table public.transactions add column if not exists user_id uuid references auth.users;

-- 3. Ensure Settings table exists (in case it wasn't created yet)
create table if not exists public.settings (
  id uuid default uuid_generate_v4() primary key,
  created_at timestamp with time zone default timezone('utc'::text, now()) not null,
  updated_at timestamp with time zone default timezone('utc'::text, now()),
  company_name text,
  cnpj text,
  ie text,
  default_overhead numeric default 20,
  default_exchange numeric default 5.65,
  brazil_api_token text,
  melhor_envio_token text,
  bling_token text,
  tiny_token text,
  gemini_key text,
  certificate_password text,
  nfe_serie text default '1',
  nfe_number text,
  nfe_environment text default 'homologacao',
  smtp_host text,
  smtp_port text,
  smtp_user text,
  smtp_pass text,
  auto_sync_sales boolean default true,
  auto_sync_stock boolean default true,
  user_id uuid references auth.users
);

-- 4. Re-apply RLS policies just in case
alter table public.inventory enable row level security;
drop policy if exists "Enable all for authenticated users" on public.inventory;
create policy "Enable all for authenticated users" on public.inventory for all to authenticated using (true) with check (true);
