<?php

namespace App\Services;

use App\Models\DailyWorkLog;
use App\Models\IdleLog;
use App\Models\ProductivityLog;
use App\Models\Task;
use App\Models\TimeLog;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class TimeTrackingService
{
    public function startTimer(int $userId, int $taskId, ?string $notes = null): TimeLog
    {
        return DB::transaction(function () use ($userId, $taskId, $notes): TimeLog {
            TimeLog::where('user_id', $userId)->whereIn('status', ['running', 'paused'])->update([
                'status' => 'stopped',
                'stopped_at' => now(),
            ]);

            return TimeLog::create([
                'user_id' => $userId,
                'task_id' => $taskId,
                'started_at' => now(),
                'status' => 'running',
                'manual_notes' => $notes,
            ]);
        });
    }

    public function pauseTimer(TimeLog $timeLog): TimeLog
    {
        if ($timeLog->status !== 'running') {
            return $timeLog;
        }

        $elapsed = max(0, $timeLog->started_at->diffInSeconds(now()));
        $timeLog->update([
            'total_seconds' => $timeLog->total_seconds + $elapsed,
            'paused_at' => now(),
            'status' => 'paused',
        ]);

        return $timeLog->refresh();
    }

    public function resumeTimer(TimeLog $timeLog): TimeLog
    {
        if ($timeLog->status !== 'paused') {
            return $timeLog;
        }

        $timeLog->update([
            'started_at' => now(),
            'paused_at' => null,
            'status' => 'running',
        ]);

        return $timeLog->refresh();
    }

    public function stopTimer(TimeLog $timeLog): TimeLog
    {
        if ($timeLog->status === 'stopped') {
            return $timeLog;
        }

        $total = $timeLog->total_seconds;
        if ($timeLog->status === 'running') {
            $total += max(0, $timeLog->started_at->diffInSeconds(now()));
        }

        $timeLog->update([
            'total_seconds' => $total,
            'stopped_at' => now(),
            'status' => 'stopped',
        ]);

        $this->recalculateForDate($timeLog->user_id, Carbon::parse($timeLog->created_at)->toDateString());

        return $timeLog->refresh();
    }

    public function logIdle(int $userId, int $timeLogId, int $idleSeconds, ?string $reason = null): IdleLog
    {
        $idle = IdleLog::create([
            'user_id' => $userId,
            'time_log_id' => $timeLogId,
            'idle_started_at' => now()->subSeconds($idleSeconds),
            'idle_ended_at' => now(),
            'idle_seconds' => $idleSeconds,
            'reason' => $reason,
        ]);

        $timeLog = TimeLog::findOrFail($timeLogId);
        $this->recalculateForDate($userId, Carbon::parse($timeLog->created_at)->toDateString());

        return $idle;
    }

    public function recalculateForDate(int $userId, string $date): void
    {
        $tracked = (int) TimeLog::where('user_id', $userId)
            ->whereDate('created_at', $date)
            ->sum('total_seconds');

        $idle = (int) IdleLog::where('user_id', $userId)
            ->whereDate('created_at', $date)
            ->sum('idle_seconds');

        $productive = max(0, $tracked - $idle);

        $taskIds = TimeLog::where('user_id', $userId)
            ->whereDate('created_at', $date)
            ->pluck('task_id')
            ->unique();

        $estimated = (int) Task::whereIn('id', $taskIds)->count() * 3600;
        $actual = $tracked;

        $score = $actual > 0 ? round(($productive / $actual) * 100, 2) : 0;

        $daily = DailyWorkLog::updateOrCreate(
            ['user_id' => $userId, 'work_date' => $date],
            [
                'total_tracked_seconds' => $tracked,
                'total_idle_seconds' => $idle,
                'productive_seconds' => $productive,
                'productivity_score' => $score,
                'estimated_seconds' => $estimated,
                'actual_seconds' => $actual,
            ]
        );

        ProductivityLog::updateOrCreate(
            ['user_id' => $userId, 'log_date' => $date, 'daily_work_log_id' => $daily->id],
            [
                'estimated_seconds' => $estimated,
                'actual_seconds' => $actual,
                'idle_seconds' => $idle,
                'productivity_score' => $score,
                'remarks' => 'Auto-calculated from time tracking engine',
            ]
        );
    }
}
