<?php

namespace App\Models;

use App\Enums\ActivityTypeEnum;
use App\Enums\ApprovalStatusEnum;
use App\Enums\PublishStatusEnum;
use App\Events\ActivityLogged;
use App\Events\RouteArticleApproved;
use Database\Factories\RouteArticleFactory;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Carbon;

/**
 * @property int $id
 * @property int $feed_id
 * @property int $platform_channel_id
 * @property int $article_id
 * @property ApprovalStatusEnum $approval_status
 * @property PublishStatusEnum $publish_status
 * @property string|null $publish_error
 * @property Carbon|null $validated_at
 * @property Carbon|null $decided_at
 * @property Carbon $created_at
 * @property Carbon $updated_at
 */
class RouteArticle extends Model
{
    /** @use HasFactory<RouteArticleFactory> */
    use HasFactory;

    protected $fillable = [
        'feed_id',
        'platform_channel_id',
        'article_id',
        'approval_status',
        'publish_status',
        'publish_error',
        'validated_at',
        'decided_at',
    ];

    protected $casts = [
        'approval_status' => ApprovalStatusEnum::class,
        'publish_status' => PublishStatusEnum::class,
        'validated_at' => 'datetime',
        'decided_at' => 'datetime',
    ];

    /**
     * @return BelongsTo<Route, $this>
     */
    public function route(): BelongsTo
    {
        return $this->belongsTo(Route::class, 'feed_id', 'feed_id')
            ->where('platform_channel_id', $this->platform_channel_id);
    }

    /**
     * @return BelongsTo<Article, $this>
     */
    public function article(): BelongsTo
    {
        return $this->belongsTo(Article::class);
    }

    /**
     * @return BelongsTo<Feed, $this>
     */
    public function feed(): BelongsTo
    {
        return $this->belongsTo(Feed::class);
    }

    /**
     * @return BelongsTo<PlatformChannel, $this>
     */
    public function platformChannel(): BelongsTo
    {
        return $this->belongsTo(PlatformChannel::class);
    }

    public function isPending(): bool
    {
        return $this->approval_status === ApprovalStatusEnum::PENDING;
    }

    public function isApproved(): bool
    {
        return $this->approval_status === ApprovalStatusEnum::APPROVED;
    }

    public function isRejected(): bool
    {
        return $this->approval_status === ApprovalStatusEnum::REJECTED;
    }

    public function approve(): void
    {
        if ($this->isApproved()) {
            return;
        }

        $this->update([
            'approval_status' => ApprovalStatusEnum::APPROVED,
            'decided_at' => now(),
        ]);

        ActivityLogged::dispatch(
            ActivityTypeEnum::APPROVE,
            "Approved \"{$this->article->title}\"",
            ['route_article_id' => $this->id],
            $this->article,
        );

        event(new RouteArticleApproved($this));
    }

    public function reject(): void
    {
        if ($this->isRejected()) {
            return;
        }

        $this->update([
            'approval_status' => ApprovalStatusEnum::REJECTED,
            'decided_at' => now(),
        ]);

        ActivityLogged::dispatch(
            ActivityTypeEnum::REJECT,
            "Rejected \"{$this->article->title}\"",
            ['route_article_id' => $this->id],
            $this->article,
        );
    }

    public function recordPublishFailed(string $reason): void
    {
        $this->update([
            'publish_status' => PublishStatusEnum::ERROR,
            'publish_error' => $reason,
        ]);
    }

    public function clearPublishFailure(): void
    {
        $this->update([
            'publish_status' => PublishStatusEnum::UNPUBLISHED,
            'publish_error' => null,
        ]);
    }

    /**
     * A failed article is never picked up again on its own; the user retries it from the Articles page.
     *
     * @param  Builder<RouteArticle>  $query
     * @return Builder<RouteArticle>
     */
    public function scopeDueForPublishing(Builder $query): Builder
    {
        return $query->where('publish_status', '!=', PublishStatusEnum::ERROR);
    }

    /**
     * @param  Builder<RouteArticle>  $query
     * @return Builder<RouteArticle>
     */
    public function scopeFailed(Builder $query): Builder
    {
        return $query->where('publish_status', PublishStatusEnum::ERROR);
    }
}
