-- 3D Printing Module Migration

-- 1. PRINTERS Table
create table if not exists public.printers (
  id uuid default uuid_generate_v4() primary key,
  created_at timestamp with time zone default timezone('utc'::text, now()) not null,
  name text not null,
  power_watts numeric default 0, -- Power consumption in Watts
  depreciation_per_hour numeric default 0, -- Estimated depreciation cost per hour
  user_id uuid references auth.users
);

-- 2. FILAMENTS Table
create table if not exists public.filaments (
  id uuid default uuid_generate_v4() primary key,
  created_at timestamp with time zone default timezone('utc'::text, now()) not null,
  name text not null, -- e.g. "PLA Generico"
  brand text,
  material text, -- PLA, PETG, ABS, etc.
  color text,
  density_g_cm3 numeric default 1.24, -- Optional, for volume calc
  spool_weight_g numeric default 1000, -- e.g. 1000g (1kg)
  price_brl numeric default 0, -- Cost of the spool
  temp_nozzle integer,
  temp_bed integer,
  user_id uuid references auth.users
);

-- 3. PRINT JOBS / CALCULATIONS
create table if not exists public.print_jobs (
  id uuid default uuid_generate_v4() primary key,
  created_at timestamp with time zone default timezone('utc'::text, now()) not null,
  name text not null, -- Project/Part name
  
  -- Inputs
  printer_id uuid references public.printers,
  filament_id uuid references public.filaments,
  weight_g numeric default 0,
  print_time_hours numeric default 0,
  
  -- Costs Snapshot (Calculated at creation time)
  energy_cost numeric default 0,
  filament_cost numeric default 0,
  depreciation_cost numeric default 0,
  additional_cost numeric default 0,
  
  total_cost numeric default 0,
  markup_percentage numeric default 0,
  final_price numeric default 0,
  
  status text default 'Draft', -- Draft, Printing, Completed
  user_id uuid references auth.users
);

-- 4. SETTINGS Update (Electricity Cost)
-- Adding a column safely
do $$ 
begin 
  if not exists (select 1 from information_schema.columns where table_name='settings' and column_name='electricity_cost_kwh') then
    alter table public.settings add column electricity_cost_kwh numeric default 0.90;
  end if;
end $$;

-- Enable RLS
alter table public.printers enable row level security;
alter table public.filaments enable row level security;
alter table public.print_jobs enable row level security;

-- Simple Policies (adjust as needed for authenticated users)
create policy "Enable all for users based on user_id" on public.printers for all using (auth.uid() = user_id);
create policy "Enable all for users based on user_id" on public.filaments for all using (auth.uid() = user_id);
create policy "Enable all for users based on user_id" on public.print_jobs for all using (auth.uid() = user_id);
