<?php

namespace App\Services;

use App\Models\WipEntry;
use Illuminate\Database\Eloquent\Model;

class WipService
{
    public function calculateUnits(int $seconds): int
    {
        return max(1, (int) ceil($seconds / 360));
    }

    public function calculateHours(int $units): float
    {
        return round($units / 10, 2);
    }

    public function create(array $data, ?Model $source = null): WipEntry
    {
        $seconds = (int) ($data['seconds'] ?? 0);
        $units = (int) ($data['units'] ?? $this->calculateUnits($seconds));
        $solicitor = app(\App\Models\Solicitor\Solicitor::class);
        
        return WipEntry::create([
            'solicitor_id' => $data['solicitor_id'] ?? $solicitor?->id,
            'client_id' => $data['client_id'] ?? null,
            'claim_id' => $data['claim_id'] ?? null,
            'user_id' => $data['user_id'] ?? auth()->id(),
            'source_type' => $source ? $source->getMorphClass() : null,
            'source_id' => $source ? $source->getKey() : null,
            'activity_type' => $data['activity_type'],
            'seconds' => $seconds,
            'units' => $units,
            'hours' => $this->calculateHours($units),
            'description' => $data['description'] ?? null,
            'started_at' => $data['started_at'] ?? null,
            'ended_at' => $data['ended_at'] ?? null,
            'is_manual' => $data['is_manual'] ?? false,
        ]);
    }
}