<?php

namespace App\Services\Expenses;

use App\Models\Expense;
use Illuminate\Support\Facades\DB;

class ExpenseQueryService
{
    public function listAll(): array
    {
        return $this->baseQuery()
            ->orderByDesc('expenses.created_at')
            ->get()
            ->map(fn ($row) => (array) $row)
            ->all();
    }

    public function findById(int $id): ?array
    {
        $row = $this->baseQuery()
            ->where('expenses.id', $id)
            ->first();

        return $row ? (array) $row : null;
    }

    private function baseQuery()
    {
        return Expense::query()
            ->selectRaw('
                expenses.*,
                u.firstname AS purchaser_firstname,
                u.lastname AS purchaser_lastname,
                approver.firstname AS approver_firstname,
                approver.lastname AS approver_lastname
            ')
            ->leftJoin('users as u', 'u.id', '=', 'expenses.purchased_by')
            ->leftJoin('users as approver', 'approver.id', '=', 'expenses.approved_by');
    }
}
