<?php

namespace App\Modules\HR\Shifts\Support;

use App\Modules\HR\Shifts\Models\Shift;
use Carbon\CarbonImmutable;

final class ShiftScheduleEndpoints
{
    public static function shiftStartOnDate(Shift $shift, CarbonImmutable $shiftCalendarDay): CarbonImmutable
    {
        $hm = self::rawTime($shift, 'start_time');

        return $shiftCalendarDay->setTimeFromTimeString($hm);
    }

    public static function shiftEndOnDate(Shift $shift, CarbonImmutable $shiftCalendarDay): CarbonImmutable
    {
        $start = self::shiftStartOnDate($shift, $shiftCalendarDay);
        $hmEnd = self::rawTime($shift, 'end_time');
        $endCandidate = $shiftCalendarDay->setTimeFromTimeString($hmEnd);
        if ($endCandidate->lte($start)) {
            return $endCandidate->addDay();
        }

        return $endCandidate;
    }

    public static function normalizeHm(string|object $value): string
    {
        if (is_object($value) && method_exists($value, 'format')) {
            return $value->format('H:i:s');
        }
        $v = (string) $value;
        if (strlen($v) === 5) {
            return $v.':00';
        }

        return $v;
    }

    private static function rawTime(Shift $shift, string $column): string
    {
        $v = $shift->getAttributes()[$column] ?? '';

        return self::normalizeHm((string) $v);
    }
}
