<?php

namespace App\Tests\Feature\Manga;

use App\Entity\Manga;
use App\Entity\Chapter;
use App\Factory\MangaFactory;
use App\Factory\ChapterFactory;
use App\Tests\Feature\AbstractApiTestCase;
use Symfony\Component\HttpFoundation\Response;
use Zenstruck\Foundry\Test\Factories;
use Zenstruck\Foundry\Test\ResetDatabase;

class DeleteMangaTest extends AbstractApiTestCase
{
    use ResetDatabase, Factories;

    public function test_it_deletes_manga_with_chapters(): void
    {
        // Arrange
        $manga = MangaFactory::createOne([
            'title' => 'One Piece',
            'slug' => 'one-piece'
        ]);

        // Create chapters for the manga
        ChapterFactory::createMany(3, [
            'manga' => $manga,
            'number' => 1.0,
            'title' => 'Chapter 1',
            'visible' => true
        ]);

        ChapterFactory::createMany(2, [
            'manga' => $manga,
            'number' => 2.0,
            'title' => 'Chapter 2',
            'visible' => true
        ]);

        ChapterFactory::createMany(1, [
            'manga' => $manga,
            'number' => 3.0,
            'title' => 'Chapter 3',
            'visible' => true
        ]);

        $mangaId = $manga->getId();

        // Verify chapters exist before deletion
        $chaptersBefore = $this->entityManager->getRepository(Chapter::class)->findBy(['manga' => $mangaId]);
        $this->assertCount(6, $chaptersBefore);

        // Act
        static::createClient()->request('DELETE', "/api/mangas/{$mangaId}");

        // Then
        $this->assertResponseStatusCodeSame(204);

        // Verify the manga was deleted
        $freshManga = $this->entityManager->find(Manga::class, $mangaId);
        $this->assertNull($freshManga);

        // Verify all chapters were also deleted (cascade)
        $chaptersAfter = $this->entityManager->getRepository(Chapter::class)->findBy(['manga' => $mangaId]);
        $this->assertCount(0, $chaptersAfter);
    }

    public function test_it_returns_404_for_non_existent_manga(): void
    {
        // When
        static::createClient()->request('DELETE', '/api/mangas/999999');

        // Then
        $this->assertResponseStatusCodeSame(404);
    }

}
