-- Projects table: per-project metadata that doesn't live on entries.
-- Currently just `income_usd` (manually entered) + `notes`, but designed
-- to grow. Key is the (operator, client, project) tuple — same grouping
-- the /projects page uses.
--
-- RLS: owners + super_admins only. Managers can't read or write. That
-- means the LEFT JOIN in project_summary returns NULL for non-owners,
-- and income/margin never leak to a manager even through a UI bug.

create table if not exists public.projects (
  id uuid primary key default gen_random_uuid(),
  org_id uuid not null references public.organizations(id) on delete cascade,
  operator text,
  client text,
  project text,
  income_usd numeric(12, 2),
  notes text,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now()
);

-- NULL-safe uniqueness on the project key. The columns are nullable
-- (a project missing operator/client/project is still a valid grouping
-- on the /projects page), so a partial unique constraint won't work.
-- A unique index on coalesce(...) treats NULL like '' and gives us the
-- semantic we want.
drop index if exists projects_org_op_client_project_unique;
create unique index projects_org_op_client_project_unique
  on public.projects (
    org_id,
    coalesce(operator, ''),
    coalesce(client, ''),
    coalesce(project, '')
  );

drop trigger if exists projects_set_updated_at on public.projects;
create trigger projects_set_updated_at
before update on public.projects
for each row execute function public.set_updated_at();

alter table public.projects enable row level security;

-- Read: org owner or super_admin only. Managers do not get this table.
drop policy if exists "projects_select_owner" on public.projects;
create policy "projects_select_owner"
  on public.projects for select
  to authenticated
  using (
    public.is_org_owner(org_id)
    or public.is_super_admin_caller()
  );

-- Write: same gate. Use `for all` so insert/update/delete share one policy.
drop policy if exists "projects_modify_owner" on public.projects;
create policy "projects_modify_owner"
  on public.projects for all
  to authenticated
  using (
    public.is_org_owner(org_id)
    or public.is_super_admin_caller()
  )
  with check (
    public.is_org_owner(org_id)
    or public.is_super_admin_caller()
  );

comment on table public.projects is
  'Per-project metadata (currently just income). Keyed by (org_id, operator, client, project), NULL-safe. RLS: owner / super_admin only.';

-- ============================================================
-- Updated project_summary RPC: LEFT JOINs projects to surface
-- income_usd. Non-owners see NULL income via RLS.
-- ============================================================
drop function if exists public.project_summary(
  uuid, timestamp, timestamp, text, uuid, text, text, text, text, text, text, uuid, boolean
);

create or replace function public.project_summary(
  p_org_id uuid,
  p_start timestamp default null,
  p_end timestamp default null,
  p_status text default 'all',
  p_batch uuid default null,
  p_q text default null,
  p_project text default null,
  p_user text default null,
  p_source_email text default null,
  p_client text default null,
  p_operator text default null,
  p_imported_by uuid default null,
  p_missing_info boolean default false
)
returns table (
  operator text,
  client text,
  project text,
  row_count bigint,
  billout_seconds bigint,
  cost_usd numeric,
  income_usd numeric
)
language sql
stable
security invoker
set search_path = public
as $$
  with filtered as (
    select te.*
    from public.time_entries te
    where te.org_id = p_org_id
      and (p_start is null or te.start_at >= p_start)
      and (p_end is null or te.start_at < p_end)
      and (p_batch is null or te.import_id = p_batch)
      and (
        p_status = 'all'
        or (p_status = 'pending'
            and te.transferred_at is null
            and te.team_member_id is not null
            and te.converted_duration_seconds is not null
            and te.operator is not null
            and te.client is not null
            and te.project is not null
            and te.description is not null
            and te.end_at is not null
            and te.source_user_email is not null
            and te.converted_user is not null)
        or (p_status = 'transferred' and te.transferred_at is not null)
        or (p_status = 'blocked'
            and te.transferred_at is null
            and (te.team_member_id is null
                 or te.converted_duration_seconds is null
                 or te.operator is null
                 or te.client is null
                 or te.project is null
                 or te.description is null
                 or te.end_at is null
                 or te.source_user_email is null
                 or te.converted_user is null))
      )
      and (
        p_q is null
        or te.project ilike '%' || p_q || '%'
        or te.description ilike '%' || p_q || '%'
        or te.source_user_email ilike '%' || p_q || '%'
        or te.client ilike '%' || p_q || '%'
      )
      and (p_project is null or te.project ilike '%' || p_project || '%')
      and (p_user is null or te.converted_user ilike '%' || p_user || '%')
      and (
        p_source_email is null
        or te.source_user_email ilike '%' || p_source_email || '%'
      )
      and (p_client is null or te.client ilike '%' || p_client || '%')
      and (p_operator is null or te.operator ilike '%' || p_operator || '%')
      and (
        p_imported_by is null
        or exists (
          select 1 from public.clockify_imports ci
          where ci.id = te.import_id and ci.imported_by = p_imported_by
        )
      )
      and (
        coalesce(p_missing_info, false) = false
        or (te.operator is null or te.client is null or te.project is null)
      )
  ),
  agg as (
    select
      operator,
      client,
      project,
      count(*)::bigint as row_count,
      coalesce(sum(converted_duration_seconds), 0)::bigint as billout_seconds,
      coalesce(sum(billout_cost_usd), 0)::numeric as cost_usd
    from filtered
    group by 1, 2, 3
  )
  select
    agg.operator,
    agg.client,
    agg.project,
    agg.row_count,
    agg.billout_seconds,
    agg.cost_usd,
    p.income_usd
  from agg
  left join public.projects p
    on p.org_id = p_org_id
    and p.operator is not distinct from agg.operator
    and p.client is not distinct from agg.client
    and p.project is not distinct from agg.project
$$;
