<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\DocumentHeader;
use App\Services\InvoiceBalanceService;
use Illuminate\Http\Request;

class InvoiceLookupController extends Controller
{
    public function __construct(private readonly InvoiceBalanceService $balances)
    {
    }

    public function search(Request $request)
    {
        $q = trim((string) $request->query('q', ''));

        $invoices = DocumentHeader::query()
            ->where('type', 'invoice')
            ->when($q !== '', fn ($query) => $query->where('document_number', 'like', '%' . $q . '%'))
            ->orderByDesc('id')
            ->limit(20)
            ->get(['id', 'document_number', 'customer_account_id', 'inclusive_total', 'status']);

        return response()->json($invoices);
    }

    public function show(DocumentHeader $invoice)
    {
        abort_unless($invoice->type === 'invoice', 404);

        $invoice->load('customer');
        $outstanding = $this->balances->outstanding($invoice);

        return response()->json([
            'id' => $invoice->id,
            'document_number' => $invoice->document_number,
            'customer_account_id' => $invoice->customer_account_id,
            'customer_label' => $invoice->customer?->customer_code . ' - ' . $invoice->customer?->customer_account,
            'outstanding' => $outstanding,
        ]);
    }
}

