<?php

namespace Database\Factories;

use App\Enums\ApprovalStatusEnum;
use App\Models\Article;
use App\Models\Feed;
use App\Models\PlatformChannel;
use App\Models\Route;
use App\Models\RouteArticle;
use Illuminate\Database\Eloquent\Factories\Factory;

class RouteArticleFactory extends Factory
{
    protected $model = RouteArticle::class;

    public function definition(): array
    {
        return [
            'feed_id' => Feed::factory(),
            'platform_channel_id' => PlatformChannel::factory(),
            'article_id' => Article::factory(),
            'approval_status' => ApprovalStatusEnum::PENDING,
            'validated_at' => null,
        ];
    }

    public function configure(): static
    {
        return $this->afterMaking(function (RouteArticle $routeArticle) {
            // Ensure a route exists for this feed+channel combination
            Route::firstOrCreate(
                [
                    'feed_id' => $routeArticle->feed_id,
                    'platform_channel_id' => $routeArticle->platform_channel_id,
                ],
                [
                    'is_active' => true,
                    'priority' => 50,
                ]
            );

            // Ensure the article belongs to the same feed
            if ($routeArticle->article_id) {
                $article = Article::find($routeArticle->article_id);
                if ($article && $article->feed_id !== $routeArticle->feed_id) {
                    $article->update(['feed_id' => $routeArticle->feed_id]);
                }
            }
        });
    }

    public function forRoute(Route $route): static
    {
        return $this->state(fn (array $attributes) => [
            'feed_id' => $route->feed_id,
            'platform_channel_id' => $route->platform_channel_id,
        ]);
    }

    public function pending(): static
    {
        return $this->state(fn (array $attributes) => [
            'approval_status' => ApprovalStatusEnum::PENDING,
            'decided_at' => null,
        ]);
    }

    public function approved(): static
    {
        return $this->state(fn (array $attributes) => [
            'approval_status' => ApprovalStatusEnum::APPROVED,
            'validated_at' => now(),
            'decided_at' => now(),
        ]);
    }

    public function rejected(): static
    {
        return $this->state(fn (array $attributes) => [
            'approval_status' => ApprovalStatusEnum::REJECTED,
            'validated_at' => now(),
            'decided_at' => now(),
        ]);
    }
}
