<?php

namespace App\Models;

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

class CalendarInstance extends Model
{
    protected $table = 'calendarinstances';
    public $timestamps = false;

    protected $fillable = [
        'calendarid',
        'principaluri',
        'uri',
        'displayname',
        'description',
        'calendarcolor',
        'timezone',
    ];

    protected $appends = ['is_remote'];

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

    // ui meta for this instance’s underlying calendar container
    public function meta(): HasOne
    {
        return $this->hasOne(CalendarMeta::class, 'calendar_id', 'calendarid');
    }

    // convenient computed flag (defaults false when no meta row exists)
    public function getIsRemoteAttribute(): bool
    {
        return (bool) ($this->meta?->is_remote ?? false);
    }

    /**
     *
     * common scopes
     */

    public function scopeForUser(Builder $query, User $user): Builder
    {
        return $query->where('principaluri', $user->uri);
    }

    public function scopeOrdered(Builder $query): Builder
    {
        return $query->orderBy('calendarorder')->orderBy('displayname');
    }

    public function scopeWithUiMeta(Builder $query): Builder
    {
        return $query->with('meta');
    }

    /**
     *
     * color accessors
     */

    public function resolvedColor(?string $fallback = null): string
    {
        // prefer meta color, fall back to sabre color, then default
        return calendar_color(
            ['color' => $this->meta?->color ?? $this->calendarcolor],
            $fallback
        );
    }

    public function resolvedColorFg(?string $fallback = null): string
    {
        return $this->meta?->color_fg
            ?? ($this->resolvedColor($fallback)
                ? contrast_text_color($this->resolvedColor($fallback))
                : ($fallback ?? '#ffffff'));
    }


    /**
     *
     * CalDAV accessors
     */

    public function caldavUrl(): string
    {
        // e.g. https://kithkin.lan/dav/calendars/1/48f888f3-c5c5-…/
        return url(
            '/dav/calendars/' .
            auth()->user()->email . '/' .
            $this->uri . '/'
        );
    }
}
