-- Per-project billout adjustments. Two knobs:
--   - billout_adjustment_pct: scales the project's billout (e.g. 10 = +10%).
--   - billout_adjustment_amount: adds a fixed $ on top (e.g. 500 = +$500).
-- Applied as: adjusted = raw × (1 + pct/100) + amount.
-- Owner-only — same RLS as the rest of the projects table.
--
-- Both adjustments apply to whichever billout window the user is looking
-- at (this-month / last-month / all-time / etc.). Fixed amount is added
-- once per window — pragmatic, not perfectly summable across windows,
-- but each window shows the full adjusted number. ADR #036.

alter table public.projects
  add column if not exists billout_adjustment_pct numeric(7, 4);

alter table public.projects
  add column if not exists billout_adjustment_amount numeric(12, 2);

comment on column public.projects.billout_adjustment_pct is
  'Owner-only: % markup on billout (10 = +10%). Applied per-window in project_summary / summary_by_project. NULL = no adjustment.';

comment on column public.projects.billout_adjustment_amount is
  'Owner-only: fixed $ adjustment on billout, applied once per row in summaries. NULL = no adjustment.';

-- ============================================================
-- Update project_summary to apply the adjustment.
-- ============================================================
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,
  billout_amount_usd numeric,
  billout_adjusted_usd numeric,
  billout_adjustment_pct numeric,
  billout_adjustment_amount 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,
      coalesce(sum(billout_amount_usd), 0)::numeric as billout_amount_usd
    from filtered
    group by 1, 2, 3
  )
  select
    agg.operator,
    agg.client,
    agg.project,
    agg.row_count,
    agg.billout_seconds,
    agg.cost_usd,
    agg.billout_amount_usd,
    -- Adjusted: raw × (1 + pct/100) + amount. NULL adjustment = no change.
    (
      agg.billout_amount_usd
        * (1 + coalesce(p.billout_adjustment_pct, 0) / 100)
      + coalesce(p.billout_adjustment_amount, 0)
    )::numeric as billout_adjusted_usd,
    p.billout_adjustment_pct,
    p.billout_adjustment_amount,
    p.income_usd
  from agg
  left join public.operators o
    on o.org_id = p_org_id and lower(o.name) = lower(agg.operator)
  left join public.clients c
    on c.operator_id = o.id and lower(c.name) = lower(agg.client)
  left join public.projects p
    on p.client_id = c.id and lower(p.name) = lower(agg.project)
$$;

-- ============================================================
-- Update summary_by_project (the homepage version) similarly so /
-- shows adjusted billout in its windows too.
-- ============================================================
drop function if exists public.summary_by_project(
  uuid, timestamp, timestamp, timestamp, timestamp, uuid, text, text, text, text
);

create or replace function public.summary_by_project(
  p_org_id uuid,
  p_this_start timestamp,
  p_this_end timestamp,
  p_prev_start timestamp,
  p_prev_end timestamp,
  p_imported_by uuid default null,
  p_operator text default null,
  p_client text default null,
  p_user text default null,
  p_source_email text default null
)
returns table (
  operator text,
  client text,
  project text,
  this_seconds bigint,
  prev_seconds bigint,
  all_seconds bigint,
  this_cost_usd numeric,
  prev_cost_usd numeric,
  all_cost_usd numeric,
  this_billout_usd numeric,
  prev_billout_usd numeric,
  all_billout_usd numeric,
  -- Adjusted billout per window (pct + fixed applied).
  this_billout_adj_usd numeric,
  prev_billout_adj_usd numeric,
  all_billout_adj_usd numeric
)
language sql
stable
security invoker
set search_path = public
as $$
  with agg as (
    select
      coalesce(te.operator, '(no operator)') as operator,
      coalesce(te.client, '(no client)') as client,
      coalesce(te.project, '(no project)') as project,
      coalesce(sum(case
        when te.start_at >= p_this_start and te.start_at < p_this_end
          then te.converted_duration_seconds end), 0)::bigint as this_seconds,
      coalesce(sum(case
        when te.start_at >= p_prev_start and te.start_at < p_prev_end
          then te.converted_duration_seconds end), 0)::bigint as prev_seconds,
      coalesce(sum(te.converted_duration_seconds), 0)::bigint as all_seconds,
      coalesce(sum(case
        when te.start_at >= p_this_start and te.start_at < p_this_end
          then te.billout_cost_usd end), 0)::numeric as this_cost_usd,
      coalesce(sum(case
        when te.start_at >= p_prev_start and te.start_at < p_prev_end
          then te.billout_cost_usd end), 0)::numeric as prev_cost_usd,
      coalesce(sum(te.billout_cost_usd), 0)::numeric as all_cost_usd,
      coalesce(sum(case
        when te.start_at >= p_this_start and te.start_at < p_this_end
          then te.billout_amount_usd end), 0)::numeric as this_billout_usd,
      coalesce(sum(case
        when te.start_at >= p_prev_start and te.start_at < p_prev_end
          then te.billout_amount_usd end), 0)::numeric as prev_billout_usd,
      coalesce(sum(te.billout_amount_usd), 0)::numeric as all_billout_usd
    from public.time_entries te
    where te.org_id = p_org_id
      and te.converted_duration_seconds is not null
      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 (p_operator is null or te.operator ilike '%' || p_operator || '%')
      and (p_client is null or te.client ilike '%' || p_client || '%')
      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 || '%'
      )
    group by 1, 2, 3
  )
  select
    agg.operator,
    agg.client,
    agg.project,
    agg.this_seconds,
    agg.prev_seconds,
    agg.all_seconds,
    agg.this_cost_usd,
    agg.prev_cost_usd,
    agg.all_cost_usd,
    agg.this_billout_usd,
    agg.prev_billout_usd,
    agg.all_billout_usd,
    -- Adjusted per window. Each window applies the full adjustment.
    (
      agg.this_billout_usd
        * (1 + coalesce(p.billout_adjustment_pct, 0) / 100)
      + coalesce(p.billout_adjustment_amount, 0)
    )::numeric as this_billout_adj_usd,
    (
      agg.prev_billout_usd
        * (1 + coalesce(p.billout_adjustment_pct, 0) / 100)
      + coalesce(p.billout_adjustment_amount, 0)
    )::numeric as prev_billout_adj_usd,
    (
      agg.all_billout_usd
        * (1 + coalesce(p.billout_adjustment_pct, 0) / 100)
      + coalesce(p.billout_adjustment_amount, 0)
    )::numeric as all_billout_adj_usd
  from agg
  left join public.operators o
    on o.org_id = p_org_id and lower(o.name) = lower(agg.operator)
  left join public.clients c
    on c.operator_id = o.id and lower(c.name) = lower(agg.client)
  left join public.projects p
    on p.client_id = c.id and lower(p.name) = lower(agg.project)
  order by this_seconds desc
$$;
