<?php

namespace App\Services;

use Illuminate\Support\Arr;

class ScheduleCartService
{
    public function __construct(
        private readonly ScheduleService $scheduleService,
    ) {}

    public function create(array $data): array
    {
        return $this->scheduleService->createSingleOrMultiple(
            baseData:  $this->baseScheduleData($data),
            schedules: $this->scheduleItems($data),
        );
    }

    //

    private function baseScheduleData(array $data): array
    {
        return Arr::except($data, [
            'schedules',
            'dates',
            'date',
            'period_type',
            'start_time',
            'end_time',
            'total_amount',
            'offers_meal',
        ]);
    }

    private function scheduleItems(array $data): array
    {
        if (! empty($data['schedules'])) {
            return $data['schedules'];
        }

        if (! empty($data['dates'])) {
            return array_map(
                fn (string $date) => array_merge(
                    Arr::only($data, ['period_type', 'start_time', 'end_time', 'total_amount', 'offers_meal']),
                    ['date' => $date],
                ),
                $data['dates'],
            );
        }

        return [
            Arr::only($data, ['date', 'period_type', 'start_time', 'end_time', 'total_amount', 'offers_meal']),
        ];
    }
}
