<?php

namespace App\Modules\HR\Employees\Services;

use App\Modules\HR\Employees\DTOs\EmploymentHistoryWriteData;
use App\Modules\HR\Employees\Models\Employee;
use App\Modules\HR\Employees\Models\EmployeeEmploymentHistory;
use App\Modules\HR\Employees\Repositories\EmployeeEmploymentHistoryRepository;

class EmployeeEmploymentHistoryService
{
    public function __construct(
        private readonly EmployeeEmploymentHistoryRepository $histories,
        private readonly EmployeeProfileActivityLogger $activity,
    ) {}

    public function store(Employee $employee, EmploymentHistoryWriteData $data): EmployeeEmploymentHistory
    {
        $history = $this->histories->create(array_merge($data->toArray(), [
            'tenant_id' => $employee->tenant_id,
            'employee_id' => $employee->id,
            'created_by' => auth()->id(),
        ]));
        $this->syncEmployee($employee, $data);
        $this->log($employee, 'employment_history_created', $data->type);

        return $history;
    }

    public function update(Employee $employee, EmployeeEmploymentHistory $history, EmploymentHistoryWriteData $data): void
    {
        $this->histories->update($history, $data->toArray());
        $this->syncEmployee($employee, $data);
        $this->log($employee, 'employment_history_updated', $data->type);
    }

    public function destroy(Employee $employee, EmployeeEmploymentHistory $history): void
    {
        $this->histories->delete($history);
        $this->log($employee, 'employment_history_deleted', $history->type->value);
    }

    private function syncEmployee(Employee $employee, EmploymentHistoryWriteData $data): void
    {
        if (! ($data->meta['sync_employee'] ?? false)) {
            return;
        }
        $allowed = array_intersect_key($data->meta, array_flip(['salary', 'department_id', 'position_id']));
        if ($allowed !== []) {
            $employee->update($allowed);
        }
    }

    private function log(Employee $employee, string $action, string $type): void
    {
        $this->activity->log($employee, $action, __('employees.employment_history.activity', [
            'type' => __('employees.employment_history.types.'.$type),
            'name' => $employee->full_name,
        ]));
    }
}
