alter table if exists public.submission_signs enable row level security;

drop policy if exists "Team all submission_signs" on public.submission_signs;
create policy "Team all submission_signs" on public.submission_signs
for all
using (get_my_role() = 'team')
with check (get_my_role() = 'team');

drop policy if exists "Client reads assigned company submission_signs" on public.submission_signs;
create policy "Client reads assigned company submission_signs" on public.submission_signs
for select
using (
  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()
  )
);

drop policy if exists "Client inserts assigned company submission_signs" on public.submission_signs;
create policy "Client inserts assigned company submission_signs" on public.submission_signs
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()
  )
);

drop policy if exists "External reads assigned submission_signs" on public.submission_signs;
create policy "External reads assigned submission_signs" on public.submission_signs
for select
using (
  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()
  )
);

drop policy if exists "External inserts assigned submission_signs" on public.submission_signs;
create policy "External inserts assigned submission_signs" on public.submission_signs
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()
  )
);
