<?php

namespace App\Services;

use App\Models\LeasingRecord;
use Illuminate\Database\Eloquent\Builder;

class SearchService
{
    /**
     * Search vehicle records with filters.
     */
    public function search(string $query, array $filters = [])
    {
        $searchQuery = LeasingRecord::query()
            ->where(function (Builder $q) use ($query) {
                $q->where('nopol', 'LIKE', "%{$query}%")
                  ->orWhere('rangka', 'LIKE', "%{$query}%")
                  ->orWhere('mesin', 'LIKE', "%{$query}%");
            })
            ->where('record_status', 'active');

        // Apply Leasing Filter
        if (!empty($filters['leasing_profile_id'])) {
            $searchQuery->where('leasing_profile_id', $filters['leasing_profile_id']);
        }

        // Apply Branch Filter
        if (!empty($filters['branch_id'])) {
            $searchQuery->where('branch_id', $filters['branch_id']);
        }

        return $searchQuery->with(['leasingProfile', 'branch'])->paginate(20);
    }

    /**
     * Get record details.
     * Note: Policy should handle internal_note visibility.
     */
    public function getDetails(int $id)
    {
        return LeasingRecord::with(['leasingProfile', 'branch'])->findOrFail($id);
    }
}
