<?php

namespace App\Services\Calendar;

use App\Models\CalendarInstance;
use App\Models\CalendarMeta;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class CreateCalendar
{
    public function create(User $user, array $data): CalendarInstance
    {
        $color = calendar_color($data);

        return DB::transaction(function () use ($user, $data, $color) {

            /* create master calendar container (sabre table) */
            $calId = DB::table('calendars')->insertGetId([
                'synctoken'  => 1,
                'components' => 'VEVENT',
            ]);

            /* create per-user instance (sabre table) */
            $instance = CalendarInstance::create([
                'calendarid'    => $calId,
                'principaluri'  => $user->uri,                 // your principal uri
                'uri'           => (string) Str::uuid(),       // instance slug
                'displayname'   => $data['name'],
                'description'   => $data['description'] ?? null,
                'calendarcolor' => $color,                      // keep sabre in sync
                'timezone'      => $data['timezone'],
            ]);

            /* create ui meta */
            CalendarMeta::updateOrCreate(
                ['calendar_id' => $calId], // calendar_id = sabre calendars.id (int)
                [
                    'title'     => $data['name'],
                    'color'     => $color,
                    'color_fg'  => contrast_text_color($color),
                    'is_remote' => false,
                    'is_shared' => false,
                ]
            );

            return $instance;
        });
    }
}
