set search_path = budget_app, public;

-- 1. Batch row count
select import_batch, count(*) as row_count
from staging_ptc_transactions
group by import_batch
order by import_batch desc;

-- 2. Account code master candidates
select
    account_code_raw,
    account_name_raw,
    count(*) as txn_count
from staging_ptc_transactions
where coalesce(account_code_raw, '') <> ''
group by account_code_raw, account_name_raw
order by account_code_raw, account_name_raw;

-- 3. Department master candidates
select
    department_name_raw,
    count(*) as txn_count
from staging_ptc_transactions
where coalesce(department_name_raw, '') <> ''
group by department_name_raw
order by txn_count desc, department_name_raw;

-- 4. Project code consistency check
select
    project_code_raw,
    count(distinct project_name_raw) as distinct_project_names,
    count(distinct project_type_raw) as distinct_project_types
from staging_ptc_transactions
where coalesce(project_code_raw, '') <> ''
group by project_code_raw
having count(distinct project_name_raw) > 1
    or count(distinct project_type_raw) > 1
order by project_code_raw;

-- 5. Missing key values
select
    source_row_no,
    transaction_date,
    in_out,
    account_code_raw,
    project_code_raw,
    project_name_raw,
    description_raw
from staging_ptc_transactions
where coalesce(account_code_raw, '') = ''
   or coalesce(project_code_raw, '') = ''
   or coalesce(project_name_raw, '') = ''
   or coalesce(description_raw, '') = ''
order by source_row_no;
