<?php

namespace Database\Seeders;

use App\Models\Post;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;

class PostSeeder extends Seeder
{
    public function run(): void
    {
        $author = User::first();

        $data = json_decode(
            file_get_contents(__DIR__ . '/data/posts.json'),
            true
        );

        foreach ($data as $post) {
            $excerptText = trim(strip_tags($post['excerpt']['rendered']));

            Post::updateOrCreate(
                ['slug' => $post['slug']],
                [
                    'user_id' => $author->id,
                    'title' => html_entity_decode($post['title']['rendered']),
                    'excerpt' => $excerptText !== '' ? Str::limit($excerptText, 250) : null,
                    'content' => $post['content']['rendered'],
                    'is_published' => $post['status'] === 'publish',
                    'published_at' => $post['status'] === 'publish' ? Carbon::parse($post['date']) : null,
                ]
            );
        }
    }
}
