<?php

namespace Modules\Billing\Repositories;

use Modules\Billing\DTO\BillingSettingFilter;
use Modules\Billing\Models\ServiceDepartment;
use Modules\Core\Enums\StatusEnum;

class ServiceDepartmentRepository
{
    public function all(BillingSettingFilter $filter)
    {
        return ServiceDepartment::query()
            ->when($filter->search, function ($query, $search) {
                $search = '%' . trim($search) . '%';

                $query->where(function ($q) use ($search) {
                    $q->where('name', 'LIKE', $search)
                        ->orWhere('code', 'LIKE', $search);
                });
            })
            ->when($filter->status, function ($query, $status) {
                $query->where('status', $status);
            })
            ->orderBy('id', 'desc')
            ->paginate($filter->perPage ?? 15);
    }

    public function find(int $id): ServiceDepartment
    {
        return ServiceDepartment::findOrFail($id);
    }

    public function create(array $data): ServiceDepartment
    {
        return ServiceDepartment::create([
            'name' => $data['name'],
            'code' => $data['code'] ?? null,
            'description' => $data['description'] ?? null,
            'status' => $data['status'] ?? StatusEnum::ACTIVE,
        ]);
    }

    public function update(ServiceDepartment $serviceDepartment, array $data): ServiceDepartment
    {
        $serviceDepartment->update([
            'name' => $data['name'],
            'code' => $data['code'] ?? null,
            'description' => $data['description'] ?? null,
            'status' => $data['status'] ?? StatusEnum::ACTIVE,
        ]);

        return $serviceDepartment;
    }

    public function updateStatus(ServiceDepartment $serviceDepartment, array $status): ServiceDepartment
    {
        $serviceDepartment->update([
            'status' => $status['status'] ?? StatusEnum::ACTIVE,
        ]);

        return $serviceDepartment;
    }
}
