<?php

namespace App\Services;

use App\Models\Assignment;
use App\Models\User;
use Carbon\Carbon;
use App\Services\NotificationService;

class CarryOverService
{
    public function __construct(
        private NotificationService $notificationService
    ) {}

    /**
     * Automatically carry over missed study sessions to the next day.
     * Only works for paid/trial users.
     */
    public function carryOverMissedSessions(User $user): int
    {
        if (!$user->canReceiveAutomatedFeatures()) {
            return 0;
        }

        $missedAssignments = $user->assignments()
            ->pending()
            ->where('planned_study_day', '<', Carbon::now()->startOfDay())
            ->where('status', 'pending')
            ->get();

        $carriedOver = 0;

        foreach ($missedAssignments as $assignment) {
            // Check if planned study time has passed
            if ($assignment->isPlannedStudyMissed()) {
                $this->carryOverAssignment($assignment);
                $carriedOver++;
            }
        }

        return $carriedOver;
    }

    /**
     * Carry over a single assignment to the next day.
     */
    public function carryOverAssignment(Assignment $assignment): Assignment
    {
        $nextDay = Carbon::now()->addDay();
        $sameTime = $assignment->planned_study_time;

        $assignment->update([
            'planned_study_day' => $nextDay,
            'carry_over_count' => $assignment->carry_over_count + 1,
            'last_carried_over_at' => now(),
        ]);

        // Send notification
        $this->notificationService->sendCarryOverNotification($assignment);

        return $assignment;
    }

    /**
     * Manually reschedule assignment (for free users).
     */
    public function rescheduleAssignment(Assignment $assignment, Carbon $newDate, Carbon $newTime): Assignment
    {
        $assignment->update([
            'planned_study_day' => $newDate,
            'planned_study_time' => Carbon::parse($newDate->format('Y-m-d') . ' ' . $newTime->format('H:i:s')),
        ]);

        return $assignment;
    }
}
