-- FRIMO GROUP CRM production hardening (apply AFTER 001_initial_schema.sql)
create extension if not exists pgcrypto;

alter table public.leads
  add column if not exists no_answer_count integer not null default 0 check (no_answer_count >= 0),
  add column if not exists interest_region text,
  add column if not exists assigned_team text,
  add column if not exists utm_content text,
  add column if not exists external_lead_id text;

alter table public.projects
  add column if not exists project_code text,
  add column if not exists project_type text,
  add column if not exists is_active boolean not null default true;

alter table public.units
  add column if not exists phase text,
  add column if not exists hold_by uuid references public.profiles(id),
  add column if not exists hold_note text;

alter table public.lands
  add column if not exists notes text,
  add column if not exists is_archived boolean not null default false;

create table if not exists public.audit_logs (
  id uuid primary key default gen_random_uuid(),
  actor_id uuid references public.profiles(id) on delete set null,
  entity_table text not null,
  entity_id uuid,
  action text not null check (action in ('INSERT','UPDATE','DELETE')),
  old_data jsonb,
  new_data jsonb,
  created_at timestamptz not null default now()
);
create index if not exists audit_logs_created_idx on public.audit_logs(created_at desc);
create index if not exists audit_logs_entity_idx on public.audit_logs(entity_table, entity_id, created_at desc);
alter table public.audit_logs enable row level security;
create policy "admins and team leaders read audit" on public.audit_logs for select to authenticated
  using (public.current_role() in ('super_admin','team_leader'));
revoke insert, update, delete on public.audit_logs from anon, authenticated;
grant select on public.audit_logs to authenticated;

create or replace function public.write_audit_log() returns trigger
language plpgsql security definer set search_path=public as $$
begin
  insert into public.audit_logs(actor_id,entity_table,entity_id,action,old_data,new_data)
  values(auth.uid(), TG_TABLE_NAME,
    coalesce((to_jsonb(new)->>'id')::uuid,(to_jsonb(old)->>'id')::uuid), TG_OP,
    case when TG_OP in ('UPDATE','DELETE') then to_jsonb(old) else null end,
    case when TG_OP in ('INSERT','UPDATE') then to_jsonb(new) else null end);
  if TG_OP='DELETE' then return old; else return new; end if;
end $$;

drop trigger if exists audit_leads on public.leads;
create trigger audit_leads after insert or update or delete on public.leads for each row execute function public.write_audit_log();
drop trigger if exists audit_lands on public.lands;
create trigger audit_lands after insert or update or delete on public.lands for each row execute function public.write_audit_log();
drop trigger if exists audit_units on public.units;
create trigger audit_units after insert or update or delete on public.units for each row execute function public.write_audit_log();
drop trigger if exists audit_projects on public.projects;
create trigger audit_projects after insert or update or delete on public.projects for each row execute function public.write_audit_log();

-- Enforce mandatory pipeline fields even when writes bypass the UI.
create or replace function public.validate_lead_pipeline() returns trigger
language plpgsql set search_path=public as $$
begin
  if new.stage='Follow Up' and new.next_follow_up is null then
    raise exception 'Follow Up requires next_follow_up date and time';
  end if;
  if new.stage='Lost/Low Budget' and nullif(btrim(new.lost_reason),'') is null then
    raise exception 'Lost/Low Budget requires lost_reason';
  end if;
  if new.stage='No Answer' and tg_op='UPDATE' and old.stage is distinct from new.stage then
    new.no_answer_count := old.no_answer_count + 1;
  end if;
  new.updated_at := now();
  return new;
end $$;
drop trigger if exists validate_lead_pipeline on public.leads;
create trigger validate_lead_pipeline before insert or update on public.leads for each row execute function public.validate_lead_pipeline();

-- Hold expiry returns inventory to Available. Can also be called from a scheduled job.
create or replace function public.release_expired_unit_holds() returns integer
language plpgsql security definer set search_path=public as $$
declare changed integer;
begin
  update public.units set status='available', hold_until=null, hold_by=null
  where status='hold' and hold_until is not null and hold_until <= now();
  get diagnostics changed = row_count;
  return changed;
end $$;
revoke all on function public.release_expired_unit_holds() from public, anon, authenticated;

-- Tighten staff visibility: agents may only read their own profile; admin roles can read staff directory.
drop policy if exists "profiles visible to signed in" on public.profiles;
create policy "profiles self or management" on public.profiles for select to authenticated
  using (id=auth.uid() or public.current_role() in ('super_admin','team_leader','marketing_manager'));

-- Explicitly ensure owner contact table cannot be read by marketing or other sales staff.
drop policy if exists "owner contacts protected read" on public.land_owner_contacts;
create policy "owner contacts protected read" on public.land_owner_contacts for select to authenticated
  using (public.current_role() in ('super_admin','team_leader') or created_by=auth.uid());

-- Storage remains private. Files are stored beneath a record UUID folder; the policy checks the record owner/role.
create policy "signed-in read own or manager files" on storage.objects for select to authenticated
  using (bucket_id='frimo-private' and (
    public.current_role() in ('super_admin','team_leader','marketing_manager') or
    (storage.foldername(name))[1] = auth.uid()::text
  ));
create policy "signed-in upload own files" on storage.objects for insert to authenticated
  with check (bucket_id='frimo-private' and (storage.foldername(name))[1] = auth.uid()::text);
create policy "signed-in update own files" on storage.objects for update to authenticated
  using (bucket_id='frimo-private' and ((storage.foldername(name))[1] = auth.uid()::text or public.current_role()='super_admin'))
  with check (bucket_id='frimo-private' and ((storage.foldername(name))[1] = auth.uid()::text or public.current_role()='super_admin'));

-- Add operational indexes for common list filters.
create index if not exists lands_geo_filter_idx on public.lands(region,district,neighborhood,status) where is_archived=false;
create index if not exists units_project_status_idx on public.units(project_id,status);
create index if not exists leads_stage_followup_idx on public.leads(stage,next_follow_up);
create index if not exists leads_utm_campaign_idx on public.leads(utm_campaign,utm_source);
