<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class CalendarMeta extends Model
{
    protected $table = 'calendar_meta';
    protected $primaryKey = 'calendar_id';
    public $incrementing = false;

    /* add mass-assignment for these cols */
    protected $fillable = [
        'calendar_id',
        'subscription_id',
        'mirror_calendar_id',
        'title',
        'color',
        'color_fg',
        'is_shared',
        'is_remote',
        'settings',
    ];

    protected $casts = [
        'is_shared' => 'boolean',
        'is_remote' => 'boolean',
        'settings'  => 'array',
    ];

    protected static function boot()
    {
        parent::boot();
        //
    }

    public function calendar(): BelongsTo
    {
        return $this->belongsTo(Calendar::class, 'calendar_id');
    }

    /**
     * Upsert meta for a remote-feed subscription.
     */
    public static function forSubscription(Subscription $sub): self
    {
        $color = calendar_color([], $sub->calendarcolor);

        return static::updateOrCreate(
            // ---- unique match-key (subscription_id is unique, nullable) ----
            ['subscription_id' => $sub->id],

            // ---- columns to fill / update ----
            [
                'title'     => $sub->displayname,
                'color'     => $color,
                'color_fg'  => contrast_text_color($color),
                'is_shared' => true,
                'is_remote' => true,
                // mirror_calendar_id is set later by the sync-job once the
                // shadow “mirror” calendar has been created.
            ],
        );
    }
}
