-- One-time remediation: Ashley Manor bill payments that double-counted the expense.
--
-- These bank debits settled an existing bill but were written with an expense
-- coa_account_id, so the GL posted Dr Expense / Cr Bank — re-recognizing an expense
-- already booked when the bill was entered, and never relieving Accounts Payable.
-- Clearing coa_account_id makes accounting.post_transaction_gl repost them via the
-- vendor → A/P branch as Dr A/P / Cr Bank, correcting prior periods. The matched
-- bills are already marked paid, so paid_amount is intentionally left untouched.
--
-- Match rule (matches the accrual A/P matching rule used by the app): same vendor,
-- bill not void/draft, amount within $0.01 of the bill total, debit date within
-- ±30 days of the bill's due (else issue) date. When a single bill matches, the
-- payment is linked via bill_id; ambiguous (multi-bill) matches clear coa only.
with targets as (
  select t.id as txn_id,
    (select array_agg(b.id) from accounting.bills b
      where b.company_id = t.company_id and b.vendor_id = t.vendor_id
        and b.status <> 'void' and b.status <> 'draft'
        and abs(b.total - t.amount) <= 0.01
        and t.date between (coalesce(b.due_date, b.issue_date) - interval '30 days')
                       and (coalesce(b.due_date, b.issue_date) + interval '30 days')
    ) as bill_ids
  from accounting.transactions t
  join accounting.companies c on c.id = t.company_id
  where c.name ilike 'Ashley Manor%'
    and t.type = 'debit' and t.vendor_id is not null and t.coa_account_id is not null
)
update accounting.transactions t
set coa_account_id = null,
    bill_id = case when array_length(targets.bill_ids, 1) = 1 then targets.bill_ids[1] else null end
from targets
where t.id = targets.txn_id
  and targets.bill_ids is not null;
