-- FRIMO GROUP CRM | Apply in Supabase SQL Editor
create extension if not exists pgcrypto;
create type public.app_role as enum ('super_admin','marketing_manager','team_leader','sales_agent');
create type public.lead_stage as enum ('New','No Answer','Follow Up','Meeting Scheduled','Done Deal','Lost/Low Budget');
create type public.inventory_status as enum ('available','hold','sold');
create or replace function public.current_role() returns public.app_role language sql stable security definer set search_path=public as $$ select role from public.profiles where id=auth.uid() $$;
create or replace function public.is_manager() returns boolean language sql stable security definer set search_path=public as $$ select coalesce(public.current_role() in ('super_admin','team_leader'),false) $$;

create table public.profiles (
 id uuid primary key references auth.users(id) on delete cascade,
 full_name text not null,
 email text,
 role public.app_role not null default 'sales_agent',
 is_active boolean not null default true,
 created_at timestamptz not null default now()
);
create table public.projects (
 id uuid primary key default gen_random_uuid(), name text not null,
 location text, description text, created_by uuid references public.profiles(id), created_at timestamptz not null default now()
);
create table public.units (
 id uuid primary key default gen_random_uuid(), project_id uuid not null references public.projects(id) on delete cascade,
 code text not null, unit_type text not null default 'شقة', area_sqm numeric(12,2), price numeric(14,2) not null default 0,
 status public.inventory_status not null default 'available', hold_until timestamptz,
 created_at timestamptz not null default now(), unique(project_id,code)
);
create table public.lands (
 id uuid primary key default gen_random_uuid(), region text not null, district text not null, neighborhood text not null,
 plot_number text not null, area_sqm numeric(12,2) not null check(area_sqm>0), land_type text not null default 'residential',
 building_ratio numeric(6,2), paid_amount numeric(14,2) not null default 0, required_amount numeric(14,2) not null default 0,
 ownership_type text not null check(ownership_type in ('owner','broker')), status public.inventory_status not null default 'available',
 created_by uuid not null references public.profiles(id), created_at timestamptz not null default now(), updated_at timestamptz not null default now(),
 unique(region,district,neighborhood,plot_number)
);
-- Contact data is deliberately separated: sales agents cannot SELECT this table.
create table public.land_owner_contacts (
 id uuid primary key default gen_random_uuid(), land_id uuid not null unique references public.lands(id) on delete cascade,
 owner_phone text not null, created_by uuid not null references public.profiles(id), created_at timestamptz not null default now()
);
create table public.leads (
 id uuid primary key default gen_random_uuid(), name text not null, phone text not null,
 interest_type text not null check(interest_type in ('unit','land')), interest_name text,
 source text default 'Manual', campaign text, adset text, ad text, utm_source text, utm_medium text, utm_campaign text,
 stage public.lead_stage not null default 'New', assigned_to uuid references public.profiles(id),
 next_follow_up timestamptz, lost_reason text, created_by uuid references public.profiles(id), created_at timestamptz not null default now(), updated_at timestamptz not null default now()
);
create index leads_assigned_created_idx on public.leads(assigned_to,created_at desc);
create index leads_phone_idx on public.leads(phone);
create table public.lead_activities (
 id uuid primary key default gen_random_uuid(), lead_id uuid not null references public.leads(id) on delete cascade,
 user_id uuid references public.profiles(id), activity_type text not null default 'note', note text not null,
 follow_up_at timestamptz, created_at timestamptz not null default now()
);
create index lead_activities_lead_idx on public.lead_activities(lead_id,created_at desc);
create table public.deals (
 id uuid primary key default gen_random_uuid(), lead_id uuid not null references public.leads(id), unit_id uuid references public.units(id),
 land_id uuid references public.lands(id), amount numeric(14,2) not null, status text not null default 'pending',
 closed_by uuid references public.profiles(id), closed_at timestamptz, created_at timestamptz not null default now(),
 check ((unit_id is not null)::int + (land_id is not null)::int = 1)
);
create table public.campaigns (
 id uuid primary key default gen_random_uuid(), name text not null, platform text not null, spend numeric(14,2) not null default 0,
 starts_on date, ends_on date, created_at timestamptz not null default now()
);

-- Simple round-robin assignment among active sales agents. Land/unit specialization can be added as teams are defined.
create table public.assignment_cursor (id boolean primary key default true check(id), last_assigned uuid references public.profiles(id));
alter table public.assignment_cursor enable row level security;
revoke all on public.assignment_cursor from anon, authenticated;
insert into public.assignment_cursor(id,last_assigned) values(true,null) on conflict do nothing;
create or replace function public.assign_new_lead() returns trigger language plpgsql security definer set search_path=public as $$
declare next_agent uuid;
begin
 if new.assigned_to is not null then return new; end if;
 select p.id into next_agent from public.profiles p
 where p.role='sales_agent' and p.is_active=true
 order by (p.id > coalesce((select last_assigned from public.assignment_cursor where id=true),'00000000-0000-0000-0000-000000000000'::uuid)) desc, p.created_at asc, p.id asc limit 1;
 if next_agent is not null then new.assigned_to:=next_agent; update public.assignment_cursor set last_assigned=next_agent where id=true; end if;
 return new;
end $$;
create trigger leads_round_robin before insert on public.leads for each row execute function public.assign_new_lead();

-- Profile creation for dashboard-admin provisioned accounts. Role is set by secure Edge Function afterwards.
create or replace function public.handle_new_user() returns trigger language plpgsql security definer set search_path=public as $$
begin insert into public.profiles(id,full_name,email,role) values(new.id,coalesce(new.raw_user_meta_data->>'full_name',split_part(new.email,'@',1)),new.email,'sales_agent') on conflict(id) do nothing; return new; end $$;
create trigger on_auth_user_created after insert on auth.users for each row execute function public.handle_new_user();

alter table public.profiles enable row level security;
alter table public.projects enable row level security;
alter table public.units enable row level security;
alter table public.lands enable row level security;
alter table public.land_owner_contacts enable row level security;
alter table public.leads enable row level security;
alter table public.lead_activities enable row level security;
alter table public.deals enable row level security;
alter table public.campaigns enable row level security;

create policy "profiles visible to signed in" on public.profiles for select to authenticated using (id=auth.uid() or public.current_role() in ('super_admin','team_leader','marketing_manager'));
create policy "admin manages profiles" on public.profiles for all to authenticated using(public.current_role()='super_admin') with check(public.current_role()='super_admin');
create policy "authenticated read projects" on public.projects for select to authenticated using(true);
create policy "managers manage projects" on public.projects for all to authenticated using(public.current_role() in ('super_admin','marketing_manager')) with check(public.current_role() in ('super_admin','marketing_manager'));
create policy "authenticated read units" on public.units for select to authenticated using(true);
create policy "managers manage units" on public.units for all to authenticated using(public.current_role() in ('super_admin','marketing_manager','team_leader')) with check(public.current_role() in ('super_admin','marketing_manager','team_leader'));
create policy "authenticated read lands" on public.lands for select to authenticated using(true);
create policy "authorized create lands" on public.lands for insert to authenticated with check(public.current_role() in ('super_admin','team_leader','sales_agent') and created_by=auth.uid());
create policy "authorized update lands" on public.lands for update to authenticated using(public.current_role() in ('super_admin','team_leader') or created_by=auth.uid()) with check(public.current_role() in ('super_admin','team_leader') or created_by=auth.uid());
create policy "admin delete lands" on public.lands for delete to authenticated using(public.current_role() in ('super_admin','team_leader'));
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());
create policy "owner contacts authorized insert" on public.land_owner_contacts for insert to authenticated with check(created_by=auth.uid() and (public.current_role() in ('super_admin','team_leader','sales_agent')));
create policy "owner contacts authorized update" on public.land_owner_contacts for update to authenticated using(public.current_role() in ('super_admin','team_leader') or created_by=auth.uid()) with check(public.current_role() in ('super_admin','team_leader') or created_by=auth.uid());
create policy "lead visibility" on public.leads for select to authenticated using(public.current_role() in ('super_admin','marketing_manager','team_leader') or assigned_to=auth.uid() or created_by=auth.uid());
create policy "lead creation" on public.leads for insert to authenticated with check(auth.uid() is not null);
create policy "lead updates" on public.leads for update to authenticated using(public.current_role() in ('super_admin','marketing_manager','team_leader') or assigned_to=auth.uid()) with check(public.current_role() in ('super_admin','marketing_manager','team_leader') or assigned_to=auth.uid());
create policy "lead activity visibility" on public.lead_activities for select to authenticated using(exists(select 1 from public.leads l where l.id=lead_id));
create policy "lead activity insert" on public.lead_activities for insert to authenticated with check(user_id=auth.uid() and exists(select 1 from public.leads l where l.id=lead_id));
create policy "deal visibility" on public.deals for select to authenticated using(public.current_role() in ('super_admin','marketing_manager','team_leader') or exists(select 1 from public.leads l where l.id=lead_id and l.assigned_to=auth.uid()));
create policy "deal managers write" on public.deals for all to authenticated using(public.current_role() in ('super_admin','team_leader')) with check(public.current_role() in ('super_admin','team_leader'));
create policy "campaign managers read" on public.campaigns for select to authenticated using(public.current_role() in ('super_admin','marketing_manager','team_leader'));
create policy "campaign managers write" on public.campaigns for all to authenticated using(public.current_role() in ('super_admin','marketing_manager')) with check(public.current_role() in ('super_admin','marketing_manager'));

-- Keep dashboard profile fields available to the UI; do not grant authenticated direct access to auth.users.
grant usage on schema public to authenticated;
grant select,insert,update,delete on all tables in schema public to authenticated;
revoke all on public.assignment_cursor from anon, authenticated;

-- Prevent repeated leads with the same normalized phone number.
create unique index leads_phone_normalized_unique on public.leads ((regexp_replace(phone,'[^0-9]','','g')));
-- Private file bucket for plot documents and project sales kits.
insert into storage.buckets(id,name,public,file_size_limit,allowed_mime_types)
values ('frimo-private','frimo-private',false,15728640,array['application/pdf','image/jpeg','image/png','image/webp'])
on conflict(id) do nothing;
-- File access policies are intentionally deferred until the app uses per-record storage paths.
