<?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);
    }

    /**
     * Whether a WIP entry already exists for the given polymorphic source and
     * activity type. Used to guard against duplicate WIP from retried or
     * duplicated webhooks (e.g. Twilio status callbacks), which would otherwise
     * double-bill units for the same event.
     *
     * Pass $userId to scope the check to a single agent: a call handled by more
     * than one agent (a transfer) books one entry per agent, so the dedup must
     * be per-agent rather than per-source or it would block the second agent.
     */
    public function existsForSource(Model $source, string $activityType, ?int $userId = null): bool
    {
        return WipEntry::query()
            ->where('source_type', $source->getMorphClass())
            ->where('source_id', $source->getKey())
            ->where('activity_type', $activityType)
            ->when($userId !== null, fn ($query) => $query->where('user_id', $userId))
            ->exists();
    }

    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,
        ]);
    }
}