
create type public.app_role as enum ('admin','user');

create table public.user_roles (
  id uuid primary key default gen_random_uuid(),
  user_id uuid references auth.users(id) on delete cascade not null,
  role app_role not null,
  unique(user_id, role)
);
grant select on public.user_roles to authenticated;
grant all on public.user_roles to service_role;
alter table public.user_roles enable row level security;

create or replace function public.has_role(_user_id uuid, _role app_role)
returns boolean language sql stable security definer set search_path = public as $$
  select exists(select 1 from public.user_roles where user_id=_user_id and role=_role)
$$;
create policy "own roles" on public.user_roles for select to authenticated using (user_id = auth.uid() or public.has_role(auth.uid(),'admin'));

create table public.settings (
  id int primary key default 1 check (id = 1),
  site_name text not null default 'RozTask',
  logo_url text,
  primary_color text not null default '#22e39a',
  referral_bonus numeric not null default 30,
  referral_required_tasks int not null default 2,
  min_withdrawal numeric not null default 50,
  default_task_reward numeric not null default 10,
  signup_bonus numeric not null default 20,
  telegram_link text default '',
  support_contact text default '',
  maintenance_mode boolean not null default false,
  updated_at timestamptz not null default now()
);
insert into public.settings (id) values (1);
grant select on public.settings to anon, authenticated;
grant update on public.settings to authenticated;
grant all on public.settings to service_role;
alter table public.settings enable row level security;
create policy "read settings" on public.settings for select to anon, authenticated using (true);
create policy "admin update settings" on public.settings for update to authenticated using (public.has_role(auth.uid(),'admin')) with check (public.has_role(auth.uid(),'admin'));

create table public.profiles (
  id uuid primary key references auth.users(id) on delete cascade,
  full_name text not null default '',
  mobile text not null unique,
  user_code text not null unique,
  referred_by uuid references public.profiles(id),
  referral_rewarded boolean not null default false,
  balance numeric not null default 0,
  total_earned numeric not null default 0,
  total_withdrawn numeric not null default 0,
  referral_earnings numeric not null default 0,
  is_blocked boolean not null default false,
  is_active boolean not null default true,
  created_at timestamptz not null default now()
);
grant select on public.profiles to authenticated;
grant all on public.profiles to service_role;
alter table public.profiles enable row level security;
create policy "own profile" on public.profiles for select to authenticated using (id = auth.uid() or public.has_role(auth.uid(),'admin'));

create table public.tasks (
  id uuid primary key default gen_random_uuid(),
  task_number serial,
  app_name text not null,
  description text not null default '',
  link text not null default '',
  video_url text default '',
  reward numeric not null default 10,
  is_active boolean not null default true,
  created_at timestamptz not null default now()
);
grant select, insert, update, delete on public.tasks to authenticated;
grant all on public.tasks to service_role;
alter table public.tasks enable row level security;
create policy "read active tasks" on public.tasks for select to authenticated using (is_active or public.has_role(auth.uid(),'admin'));
create policy "admin insert tasks" on public.tasks for insert to authenticated with check (public.has_role(auth.uid(),'admin'));
create policy "admin update tasks" on public.tasks for update to authenticated using (public.has_role(auth.uid(),'admin'));
create policy "admin delete tasks" on public.tasks for delete to authenticated using (public.has_role(auth.uid(),'admin'));

create table public.submissions (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references public.profiles(id) on delete cascade,
  task_id uuid not null references public.tasks(id) on delete cascade,
  screenshot_path text not null,
  status text not null default 'pending' check (status in ('pending','approved','rejected')),
  reward numeric not null default 0,
  reason text,
  created_at timestamptz not null default now(),
  reviewed_at timestamptz,
  unique(user_id, task_id)
);
grant select on public.submissions to authenticated;
grant all on public.submissions to service_role;
alter table public.submissions enable row level security;
create policy "own submissions" on public.submissions for select to authenticated using (user_id = auth.uid() or public.has_role(auth.uid(),'admin'));

create table public.withdrawals (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references public.profiles(id) on delete cascade,
  amount numeric not null check (amount > 0),
  upi_id text not null,
  status text not null default 'pending' check (status in ('pending','approved','rejected')),
  reason text,
  created_at timestamptz not null default now(),
  processed_at timestamptz
);
grant select on public.withdrawals to authenticated;
grant all on public.withdrawals to service_role;
alter table public.withdrawals enable row level security;
create policy "own withdrawals" on public.withdrawals for select to authenticated using (user_id = auth.uid() or public.has_role(auth.uid(),'admin'));

create table public.transactions (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references public.profiles(id) on delete cascade,
  type text not null,
  amount numeric not null,
  description text not null default '',
  status text not null default 'completed',
  ref_id uuid,
  created_at timestamptz not null default now()
);
grant select on public.transactions to authenticated;
grant all on public.transactions to service_role;
alter table public.transactions enable row level security;
create policy "own tx" on public.transactions for select to authenticated using (user_id = auth.uid() or public.has_role(auth.uid(),'admin'));

create table public.admin_logs (
  id uuid primary key default gen_random_uuid(),
  admin_id uuid not null,
  action text not null,
  details text not null default '',
  created_at timestamptz not null default now()
);
grant select, insert on public.admin_logs to authenticated;
grant all on public.admin_logs to service_role;
alter table public.admin_logs enable row level security;
create policy "admin read logs" on public.admin_logs for select to authenticated using (public.has_role(auth.uid(),'admin'));
create policy "admin write logs" on public.admin_logs for insert to authenticated with check (public.has_role(auth.uid(),'admin') and admin_id = auth.uid());

-- signup
create or replace function public.handle_new_user()
returns trigger language plpgsql security definer set search_path = public as $$
declare
  ref_code text := upper(trim(coalesce(new.raw_user_meta_data->>'ref','')));
  ref_id uuid;
  code text;
  bonus numeric;
begin
  loop
    code := upper(substr(md5(random()::text),1,7));
    exit when not exists(select 1 from profiles where user_code = code);
  end loop;
  if ref_code <> '' then
    select id into ref_id from profiles where user_code = ref_code;
  end if;
  select signup_bonus into bonus from settings where id=1;
  insert into profiles(id, full_name, mobile, user_code, referred_by, balance, total_earned)
  values (new.id, coalesce(new.raw_user_meta_data->>'full_name',''),
          coalesce(new.raw_user_meta_data->>'mobile', split_part(new.email,'@',1)),
          code, ref_id, coalesce(bonus,0), coalesce(bonus,0));
  insert into user_roles(user_id, role) values (new.id,'user');
  if coalesce(bonus,0) > 0 then
    insert into transactions(user_id,type,amount,description) values (new.id,'signup_bonus',bonus,'Signup bonus');
  end if;
  return new;
end $$;
create trigger on_auth_user_created after insert on auth.users for each row execute function public.handle_new_user();

-- submit task
create or replace function public.submit_task(_task_id uuid, _path text)
returns void language plpgsql security definer set search_path = public as $$
declare p profiles; t tasks;
begin
  select * into p from profiles where id = auth.uid();
  if p.id is null then raise exception 'Not signed in'; end if;
  if p.is_blocked or not p.is_active then raise exception 'Your account is blocked'; end if;
  if (select maintenance_mode from settings where id=1) then raise exception 'Site under maintenance'; end if;
  select * into t from tasks where id=_task_id and is_active;
  if t.id is null then raise exception 'Task not available'; end if;
  if _path not like auth.uid()::text || '/%' then raise exception 'Invalid screenshot'; end if;
  if exists(select 1 from submissions where user_id=p.id and task_id=_task_id and status in ('pending','approved')) then
    raise exception 'Already submitted';
  end if;
  delete from submissions where user_id=p.id and task_id=_task_id and status='rejected';
  insert into submissions(user_id,task_id,screenshot_path,reward) values (p.id,_task_id,_path,t.reward);
end $$;

-- withdrawal
create or replace function public.request_withdrawal(_amount numeric, _upi text)
returns void language plpgsql security definer set search_path = public as $$
declare p profiles; s settings; wid uuid;
begin
  select * into p from profiles where id = auth.uid() for update;
  select * into s from settings where id=1;
  if p.id is null then raise exception 'Not signed in'; end if;
  if p.is_blocked or not p.is_active then raise exception 'Your account is blocked'; end if;
  if s.maintenance_mode then raise exception 'Site under maintenance'; end if;
  if _amount < s.min_withdrawal then raise exception 'Minimum withdrawal is ₹%', s.min_withdrawal; end if;
  if _amount > p.balance then raise exception 'Insufficient balance'; end if;
  if length(trim(_upi)) < 5 or position('@' in _upi) = 0 then raise exception 'Enter a valid UPI ID'; end if;
  if exists(select 1 from withdrawals where user_id=p.id and status='pending') then raise exception 'You already have a pending withdrawal'; end if;
  update profiles set balance = balance - _amount where id=p.id;
  insert into withdrawals(user_id,amount,upi_id) values (p.id,_amount,trim(_upi)) returning id into wid;
  insert into transactions(user_id,type,amount,description,status,ref_id) values (p.id,'withdrawal',-_amount,'Withdrawal to '||trim(_upi),'pending',wid);
end $$;

-- admin: review submission
create or replace function public.admin_review_submission(_id uuid, _approve boolean, _reason text default null)
returns void language plpgsql security definer set search_path = public as $$
declare sub submissions; p profiles; s settings; cnt int;
begin
  if not has_role(auth.uid(),'admin') then raise exception 'Forbidden'; end if;
  select * into sub from submissions where id=_id for update;
  if sub.id is null or sub.status <> 'pending' then raise exception 'Already reviewed'; end if;
  if not _approve then
    update submissions set status='rejected', reason=_reason, reviewed_at=now() where id=_id;
    insert into admin_logs(admin_id,action,details) values (auth.uid(),'reject_task',_id::text||' '||coalesce(_reason,''));
    return;
  end if;
  update submissions set status='approved', reviewed_at=now(), reason=_reason where id=_id;
  update profiles set balance=balance+sub.reward, total_earned=total_earned+sub.reward where id=sub.user_id;
  insert into transactions(user_id,type,amount,description,ref_id) values (sub.user_id,'task_reward',sub.reward,'Task reward',sub.id);
  insert into admin_logs(admin_id,action,details) values (auth.uid(),'approve_task',_id::text);
  select * into p from profiles where id=sub.user_id for update;
  select * into s from settings where id=1;
  if p.referred_by is not null and not p.referral_rewarded then
    select count(*) into cnt from submissions where user_id=p.id and status='approved';
    if cnt >= s.referral_required_tasks then
      update profiles set referral_rewarded=true where id=p.id;
      update profiles set balance=balance+s.referral_bonus, total_earned=total_earned+s.referral_bonus, referral_earnings=referral_earnings+s.referral_bonus where id=p.referred_by;
      insert into transactions(user_id,type,amount,description,ref_id) values (p.referred_by,'referral_bonus',s.referral_bonus,'Referral bonus: '||p.full_name,p.id);
    end if;
  end if;
end $$;

-- admin: review withdrawal
create or replace function public.admin_review_withdrawal(_id uuid, _approve boolean, _reason text default null)
returns void language plpgsql security definer set search_path = public as $$
declare w withdrawals;
begin
  if not has_role(auth.uid(),'admin') then raise exception 'Forbidden'; end if;
  select * into w from withdrawals where id=_id for update;
  if w.id is null or w.status <> 'pending' then raise exception 'Already processed'; end if;
  if _approve then
    update withdrawals set status='approved', processed_at=now(), reason=_reason where id=_id;
    update profiles set total_withdrawn=total_withdrawn+w.amount where id=w.user_id;
    update transactions set status='approved' where ref_id=_id and type='withdrawal';
  else
    update withdrawals set status='rejected', processed_at=now(), reason=_reason where id=_id;
    update profiles set balance=balance+w.amount where id=w.user_id;
    update transactions set status='rejected' where ref_id=_id and type='withdrawal';
    insert into transactions(user_id,type,amount,description,ref_id) values (w.user_id,'refund',w.amount,'Withdrawal rejected – refunded',_id);
  end if;
  insert into admin_logs(admin_id,action,details) values (auth.uid(), case when _approve then 'approve_withdrawal' else 'reject_withdrawal' end, _id::text||' ₹'||w.amount);
end $$;

-- admin: adjust balance
create or replace function public.admin_adjust_balance(_user uuid, _amount numeric, _kind text, _reason text)
returns void language plpgsql security definer set search_path = public as $$
begin
  if not has_role(auth.uid(),'admin') then raise exception 'Forbidden'; end if;
  if coalesce(trim(_reason),'') = '' then raise exception 'Reason is required'; end if;
  if _amount = 0 then raise exception 'Amount cannot be zero'; end if;
  if _kind not in ('admin_credit','admin_debit','task_adjust','referral_adjust') then raise exception 'Invalid type'; end if;
  if (select balance from profiles where id=_user) + _amount < 0 then raise exception 'Balance cannot go negative'; end if;
  update profiles set balance=balance+_amount,
    total_earned = total_earned + greatest(_amount,0),
    referral_earnings = case when _kind='referral_adjust' then referral_earnings+_amount else referral_earnings end
  where id=_user;
  insert into transactions(user_id,type,amount,description) values (_user,_kind,_amount,'Admin: '||_reason);
  insert into admin_logs(admin_id,action,details) values (auth.uid(),'balance_'||_kind,_user::text||' ₹'||_amount||' – '||_reason);
end $$;

-- admin: update user
create or replace function public.admin_update_user(_user uuid, _name text, _mobile text, _blocked boolean, _active boolean)
returns void language plpgsql security definer set search_path = public as $$
begin
  if not has_role(auth.uid(),'admin') then raise exception 'Forbidden'; end if;
  update profiles set full_name=_name, mobile=_mobile, is_blocked=_blocked, is_active=_active where id=_user;
  insert into admin_logs(admin_id,action,details) values (auth.uid(),'update_user',_user::text||' name='||_name||' mobile='||_mobile||' blocked='||_blocked||' active='||_active);
end $$;

-- admin stats
create or replace function public.admin_stats()
returns json language plpgsql stable security definer set search_path = public as $$
begin
  if not has_role(auth.uid(),'admin') then raise exception 'Forbidden'; end if;
  return json_build_object(
    'total_users',(select count(*) from profiles),
    'active_users',(select count(*) from profiles where is_active and not is_blocked),
    'blocked_users',(select count(*) from profiles where is_blocked),
    'total_tasks',(select count(*) from tasks),
    'completed_tasks',(select count(*) from submissions where status='approved'),
    'pending_approvals',(select count(*) from submissions where status='pending'),
    'wallet_total',(select coalesce(sum(balance),0) from profiles),
    'rewards_total',(select coalesce(sum(amount),0) from transactions where type in ('task_reward','referral_bonus','signup_bonus')),
    'withdrawals_total',(select coalesce(sum(amount),0) from withdrawals where status='approved'),
    'pending_withdrawals',(select count(*) from withdrawals where status='pending'),
    'referral_total',(select coalesce(sum(amount),0) from transactions where type='referral_bonus'),
    'total_referrals',(select count(*) from profiles where referred_by is not null)
  );
end $$;

-- referrals visible to inviter (names only)
create or replace function public.my_referrals()
returns table(full_name text, created_at timestamptz, rewarded boolean) language sql stable security definer set search_path = public as $$
  select full_name, created_at, referral_rewarded from profiles where referred_by = auth.uid() order by created_at desc
$$;

revoke execute on function public.handle_new_user() from public, anon, authenticated;

insert into public.tasks(app_name,description,link,reward,video_url) values
('PhonePe','Install the app, sign up with your mobile number and complete KYC. Upload a screenshot of the home screen.','https://www.phonepe.com/',25,'https://www.youtube.com/watch?v=dQw4w9WgXcQ'),
('Groww','Download Groww, create an account and complete profile setup. Upload a screenshot of your profile page.','https://groww.in/',30,'https://www.youtube.com/watch?v=dQw4w9WgXcQ'),
('Meesho','Install Meesho, sign up and add any product to cart. Upload the cart screenshot.','https://www.meesho.com/',15,'https://www.youtube.com/watch?v=dQw4w9WgXcQ');
