drop policy if exists "Client inserts submission_files" on public.submission_files;
drop policy if exists "External inserts submission_files" on public.submission_files;

create policy "Client inserts submission_files" on public.submission_files
  for insert with check (
    get_my_role() = 'client'
    and submission_id in (
      select s.id
      from public.submissions s
      join public.tasks t on t.id = s.task_id
      join public.projects p on p.id = t.project_id
      where p.company_id = get_my_company_id()
        and s.submitted_by = auth.uid()
    )
  );

create policy "External inserts submission_files" on public.submission_files
  for insert with check (
    get_my_role() = 'external'
    and submission_id in (
      select s.id
      from public.submissions s
      join public.tasks t on t.id = s.task_id
      join public.project_members pm on pm.project_id = t.project_id
      where pm.profile_id = auth.uid()
        and s.submitted_by = auth.uid()
    )
  );
