<?php

namespace App\Models;

use App\Enums\AppRole;
use App\Enums\PartnershipStatus;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Carbon;

class Partnership extends Model
{
    protected $fillable = [
        'legacy_uuid',
        'workspace_id',
        'restaurant_name',
        'instagram_handle',
        'instagram_url',
        'status',
        'scheduled_date',
        'scheduled_time',
        'inclusions',
        'guests',
        'notes',
        'location',
        'post_url',
        'created_by',
        'managed_by_restaurant',
    ];

    protected function casts(): array
    {
        return [
            'status' => PartnershipStatus::class,
            'scheduled_date' => 'date',
            'inclusions' => 'array',
        ];
    }

    public function workspace(): BelongsTo
    {
        return $this->belongsTo(Workspace::class);
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function restaurantManager(): BelongsTo
    {
        return $this->belongsTo(User::class, 'managed_by_restaurant');
    }

    public function scopeVisibleTo(Builder $query, User $user, Workspace $workspace): Builder
    {
        $member = WorkspaceMember::query()
            ->where('workspace_id', $workspace->id)
            ->where('user_id', $user->id)
            ->first();

        if ($member === null) {
            return $query->whereRaw('1 = 0');
        }

        $query->where('workspace_id', $workspace->id);

        return match ($member->role) {
            AppRole::Influencer, AppRole::Assistant => $query,
            AppRole::Restaurant => $query->where('managed_by_restaurant', $user->id),
            AppRole::Agency => self::applyAgencyScope($query, $member),
        };
    }

    protected static function applyAgencyScope(Builder $query, WorkspaceMember $member): Builder
    {
        $paired = $member->paired_restaurant_user_id;
        if ($paired === null) {
            return $query;
        }

        return $query->where('managed_by_restaurant', $paired);
    }

    public function isVisibleTo(User $user): bool
    {
        $workspace = $this->workspace;

        return static::query()
            ->whereKey($this->id)
            ->visibleTo($user, $workspace)
            ->exists();
    }

    /** Human label for scheduled date (Today / Tomorrow / short date). */
    public function humanScheduledLabel(): ?string
    {
        if ($this->scheduled_date === null) {
            return null;
        }

        $d = $this->scheduled_date->copy()->startOfDay();
        $today = Carbon::now()->startOfDay();
        $tomorrow = $today->copy()->addDay();

        if ($d->equalTo($today)) {
            return 'Today';
        }
        if ($d->equalTo($tomorrow)) {
            return 'Tomorrow';
        }

        return $d->format('D j M');
    }

    /** One-line meal / inclusion summary from JSON inclusions. */
    public function inclusionsLine(): ?string
    {
        $inc = $this->inclusions;
        if (! is_array($inc) || $inc === []) {
            return null;
        }
        if (! empty($inc['description']) && is_string($inc['description'])) {
            return trim($inc['description']);
        }
        $parts = [];
        foreach (['starters', 'mains', 'desserts', 'drinks'] as $key) {
            if (! empty($inc[$key]) && is_numeric($inc[$key])) {
                $parts[] = (int) $inc[$key].' '.$key;
            }
        }

        return $parts === [] ? null : implode(', ', $parts);
    }
}
