<?php

namespace App\Http\Controllers\Api;

use App\Models\Invoice;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class InvoiceController extends BaseApiController
{
    protected string $model = Invoice::class;
    protected array $with = ['vendor', 'project', 'payments'];
    protected array $searchable = ['invoiceId', 'description'];
    protected array $filters = ['status' => 'status', 'vendor' => 'vendor_id', 'project' => 'project_id'];

    protected function rules(Request $request, ?Model $model = null): array
    {
        return [
            'invoiceId' => 'nullable|string',
            'vendor' => 'nullable|string|exists:vendors,id',
            'project' => 'nullable|string|exists:projects,id',
            'description' => 'nullable|string',
            'amount' => 'nullable|numeric',
            'paidAmount' => 'nullable|numeric',
            'issueDate' => 'nullable|date',
            'dueDate' => 'nullable|date',
            'status' => 'nullable|string',
            'paymentTerms' => 'nullable|string',
        ];
    }

    protected function transform(Request $request, array $data): array
    {
        foreach (['vendor' => 'vendor_id', 'project' => 'project_id'] as $k => $col) {
            if (array_key_exists($k, $data)) { $data[$col] = $data[$k]; unset($data[$k]); }
        }
        if (empty($data['invoiceId']) && empty($request->route('id'))) {
            $data['invoiceId'] = 'INV-' . str_pad((string) (Invoice::withTrashed()->count() + 1), 4, '0', STR_PAD_LEFT);
        }
        return $data;
    }
}
