<?php

namespace App\Modules\HR\Shifts\Services;

use App\Modules\HR\Shifts\Models\ShiftRotation;
use App\Modules\HR\Shifts\Repositories\ShiftWorkforceRepository;
use App\Modules\HR\Shifts\Repositories\EmployeeShiftAssignmentRepository;
use Carbon\CarbonImmutable;

class ShiftRotationService
{
    public function __construct(
        private readonly ShiftWorkforceRepository $workforce,
        private readonly EmployeeShiftAssignmentRepository $assignments,
    ) {}

    public function create(int $tenantId, array $data, int $actorId): ShiftRotation
    {
        $data['days'] = array_map(function (array $day): array {
            $day['is_day_off'] = (bool) ($day['is_day_off'] ?? empty($day['shift_id']));

            return $day;
        }, $data['days']);

        $rotation = $this->workforce->createRotation($tenantId, $data);
        $this->scheduleAssignments($tenantId, $rotation, $data, $actorId);

        return $rotation;
    }

    private function scheduleAssignments(int $tenantId, ShiftRotation $rotation, array $data, int $actorId): void
    {
        $employeeIds = $data['employee_ids'] ?? [];
        if ($employeeIds === []) {
            return;
        }
        $start = CarbonImmutable::parse($data['starts_at'])->startOfDay();
        $days = $rotation->days->values();
        foreach ($employeeIds as $employeeId) {
            foreach (range(0, 89) as $offset) {
                $pattern = $days[$offset % $days->count()];
                if ($pattern->is_day_off || $pattern->shift_id === null) {
                    continue;
                }
                $date = $start->addDays($offset);
                $this->assignments->create([
                    'tenant_id' => $tenantId,
                    'employee_id' => $employeeId,
                    'shift_id' => $pattern->shift_id,
                    'starts_at' => $date,
                    'ends_at' => $date->endOfDay(),
                    'is_active' => false,
                    'assigned_by' => $actorId,
                ]);
            }
        }
    }
}
