<?php

declare(strict_types=1);

namespace App\Models;

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

class Discussion extends Model
{
    protected $guarded = ['id', 'created_at', 'updated_at'];

    public const STATUS_ACTIVE = 'active';

    public const STATUS_ENDED = 'ended';

    public const STATUS_DELETED = 'deleted';

    public static function statusOptions(): array
    {
        return [
            self::STATUS_ACTIVE => 'فعال',
            self::STATUS_ENDED => 'پایان‌یافته',
            self::STATUS_DELETED => 'حذف شده',
        ];
    }

    public function project(): BelongsTo
    {
        return $this->belongsTo(Project::class, 'project_id');
    }

    public function messages(): HasMany
    {
        return $this->hasMany(DiscussionMessage::class, 'discussion_id');
    }

    public function latestMessage(): HasOne
    {
        return $this->hasOne(DiscussionMessage::class, 'discussion_id')->latestOfMany();
    }

    public function participants(): HasMany
    {
        return $this->hasMany(DiscussionParticipant::class, 'discussion_id');
    }

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

    public function scopeActive(Builder $query): Builder
    {
        return $query->where('status', self::STATUS_ACTIVE);
    }

    public function scopeHistory(Builder $query): Builder
    {
        return $query->whereIn('status', [self::STATUS_ENDED, self::STATUS_DELETED]);
    }

    public function isActive(): bool
    {
        return $this->status === self::STATUS_ACTIVE;
    }

    public function isParticipant(User $user): bool
    {
        return $this->participants()->where('user_id', $user->id)->exists();
    }

    public function isBlocked(User $user): bool
    {
        return $this->participants()
            ->where('user_id', $user->id)
            ->where('is_blocked', true)
            ->exists();
    }

    /**
     * @return list<int>
     */
    public static function projectUserIds(Project $project): array
    {
        $project->loadMissing('producer');

        return array_values(array_unique(array_filter([
            $project->user_id,
            $project->created_by,
            $project->producer?->user_id,
        ])));
    }
}
