<?php

namespace App\Modules\HR\Employees\Services;

use App\Modules\HR\Employees\DTOs\EmployeeAssetWriteData;
use App\Modules\HR\Employees\Models\Employee;
use App\Modules\HR\Employees\Models\EmployeeAssetAssignment;
use App\Modules\HR\Employees\Repositories\EmployeeAssetAssignmentRepository;

class EmployeeAssetAssignmentService
{
    public function __construct(
        private readonly EmployeeAssetAssignmentRepository $assignments,
        private readonly EmployeeProfileActivityLogger $activity,
    ) {}

    public function store(Employee $employee, EmployeeAssetWriteData $data): EmployeeAssetAssignment
    {
        $row = $this->assignments->create(array_merge($data->toArray(), [
            'tenant_id' => (int) $employee->tenant_id,
            'employee_id' => (int) $employee->id,
            'assigned_by' => auth()->id(),
        ]));

        $this->activity->log($employee, 'asset_assigned', __('activity_logs.actions.employee_asset_assigned', [
            'name' => $employee->full_name,
            'asset' => $row->asset_name,
        ]));

        return $row;
    }

    public function update(
        Employee $employee,
        EmployeeAssetAssignment $assignment,
        EmployeeAssetWriteData $data,
    ): EmployeeAssetAssignment {
        $updated = $this->assignments->update($assignment, $data->toArray());
        $this->activity->log($employee, 'asset_updated', __('activity_logs.actions.employee_asset_updated', [
            'name' => $employee->full_name,
            'asset' => $updated->asset_name,
        ]));

        return $updated;
    }

    public function destroy(Employee $employee, EmployeeAssetAssignment $assignment): void
    {
        $label = $assignment->asset_name;
        $this->assignments->delete($assignment);
        $this->activity->log($employee, 'asset_removed', __('activity_logs.actions.employee_asset_removed', [
            'name' => $employee->full_name,
            'asset' => $label,
        ]));
    }
}
