<?php

namespace App\Services\Ticket;

use App\Models\TicketIncidentType;

class TicketIncidentTypeService
{
    public function list(array $filters = [])
    {
        return TicketIncidentType::query()
            ->when(
                ! empty($filters['search']),
                fn ($query) => $query->where('name', 'ILIKE', "%{$filters['search']}%")
            )
            ->when(
                array_key_exists('is_active', $filters) && $filters['is_active'] !== '',
                fn ($query) => $query->where(
                    'is_active',
                    filter_var($filters['is_active'], FILTER_VALIDATE_BOOLEAN)
                )
            )
            ->orderBy('name')
            ->paginate($filters['per_page'] ?? 10);
    }

    public function create(array $data): TicketIncidentType
    {
        return TicketIncidentType::create([
            'name' => $data['name'],
            'is_active' => $data['is_active'] ?? true,
        ]);
    }

    public function update(
        TicketIncidentType $ticketIncidentType,
        array $data
    ): TicketIncidentType {
        $ticketIncidentType->update([
            'name' => $data['name'],
            'is_active' => $data['is_active'],
        ]);

        return $ticketIncidentType->fresh();
    }

    public function delete(TicketIncidentType $ticketIncidentType): void
    {
        $ticketIncidentType->delete();
    }
}
