-- 0002_jobs.sql — Phase 1
-- Tables: jobs, job_search_criteria
set search_path to ordinarthur_os, public;

create table if not exists ordinarthur_os.jobs (
  id uuid primary key default gen_random_uuid(),
  source text not null,                 -- 'Indeed','WeLoveDevs',...
  source_url text not null unique,      -- clé de dedup
  title text not null,
  company text,
  description text,
  location text,
  remote_type text check (remote_type in ('remote','hybrid','onsite')),
  salary_min int,
  salary_max int,
  stack text[] not null default '{}',
  apply_url text,
  first_seen_at timestamptz not null default now(),
  last_seen_at  timestamptz not null default now(),
  archived boolean not null default false,
  starred boolean not null default false,
  applied_at timestamptz,
  notes text
);
create index if not exists jobs_last_seen_idx on ordinarthur_os.jobs(last_seen_at desc);
create index if not exists jobs_archived_idx on ordinarthur_os.jobs(archived);
create index if not exists jobs_remote_type_idx on ordinarthur_os.jobs(remote_type);
create index if not exists jobs_stack_gin on ordinarthur_os.jobs using gin (stack);

alter table ordinarthur_os.jobs enable row level security;
drop policy if exists jobs_service_role on ordinarthur_os.jobs;
create policy jobs_service_role on ordinarthur_os.jobs
  for all using (auth.role() = 'service_role')
          with check (auth.role() = 'service_role');

create table if not exists ordinarthur_os.job_search_criteria (
  id uuid primary key default gen_random_uuid(),
  name text,
  titles text[] not null default '{}',
  locations text[] not null default '{}',
  stack text[] not null default '{}',
  remote_types text[] not null default '{}',
  salary_min int,
  active boolean not null default true,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now()
);
create index if not exists job_criteria_active_idx on ordinarthur_os.job_search_criteria(active);

alter table ordinarthur_os.job_search_criteria enable row level security;
drop policy if exists job_criteria_service_role on ordinarthur_os.job_search_criteria;
create policy job_criteria_service_role on ordinarthur_os.job_search_criteria
  for all using (auth.role() = 'service_role')
          with check (auth.role() = 'service_role');
