<?php

namespace App\Modules\HR\Assets\Repositories;

use App\Modules\HR\Assets\Models\Asset;
use App\Modules\HR\Assets\Models\AssetMovement;
use App\Modules\HR\Employees\Models\EmployeeAssetAssignment;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class AssetRepository
{
    public function details(Asset $asset): Asset
    {
        return $asset->load(['currentEmployee', 'movements.employee', 'movements.createdBy']);
    }

    public function paginate(int $tenantId): LengthAwarePaginator
    {
        return Asset::query()->where('tenant_id', $tenantId)
            ->with('currentEmployee:id,full_name,tenant_id')->orderBy('asset_code')->paginate(20);
    }

    /** @param array<string, mixed> $data */
    public function create(array $data): Asset
    {
        return Asset::query()->create($data);
    }

    /** @param array<string, mixed> $data */
    public function update(Asset $asset, array $data): Asset
    {
        $asset->update($data);

        return $asset->fresh(['currentEmployee', 'movements.employee']);
    }

    /** @param array<string, mixed> $data */
    public function movement(array $data): AssetMovement
    {
        return AssetMovement::query()->create($data);
    }

    public function activeAssignment(int $assetId): ?EmployeeAssetAssignment
    {
        return EmployeeAssetAssignment::query()
            ->where('external_asset_id', $assetId)->where('status', 'assigned')->latest()->first();
    }

    /** @param array<string, mixed> $data */
    public function createAssignment(array $data): EmployeeAssetAssignment
    {
        return EmployeeAssetAssignment::query()->create($data);
    }

    /** @param array<string, mixed> $data */
    public function updateAssignment(EmployeeAssetAssignment $assignment, array $data): void
    {
        $assignment->update($data);
    }
}
