package org.raddatz.familienarchiv.geschichte;

import org.junit.jupiter.api.Test;
import org.raddatz.familienarchiv.PostgresContainerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import software.amazon.awssdk.services.s3.S3Client;

import java.util.UUID;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

/**
 * Raw-SQL constraint tests for geschichten — deliberately NOT @Transactional at
 * class level (see JourneyItemConstraintsTest for the rationale).
 *
 * The V75 CHECK is the atomic backstop for GeschichteService.MAX_INTRO_LENGTH on
 * the verbatim JOURNEY intro write path. STORY bodies are intentionally exempt.
 */
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@ActiveProfiles("test")
@Import(PostgresContainerConfig.class)
class GeschichteConstraintsTest {

    @MockitoBean
    S3Client s3Client;

    @Autowired JdbcTemplate jdbcTemplate;

    private UUID insertGeschichte(String type, String body) {
        UUID id = UUID.randomUUID();
        jdbcTemplate.update(
                "INSERT INTO geschichten (id, title, body, status, type, created_at, updated_at) "
                        + "VALUES (?, ?, ?, 'DRAFT', ?, now(), now())",
                id, "Constraints-Test", body, type);
        return id;
    }

    @Test
    void journey_intro_check_rejects_4001_chars() {
        assertThatThrownBy(() -> insertGeschichte("JOURNEY", "x".repeat(4001)))
                .isInstanceOf(DataIntegrityViolationException.class);
    }

    @Test
    void journey_intro_check_accepts_exactly_4000_chars() {
        UUID id = insertGeschichte("JOURNEY", "x".repeat(4000));
        Integer count = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM geschichten WHERE id = ?", Integer.class, id);
        assertThat(count).isEqualTo(1);
    }

    @Test
    void story_bodies_are_not_constrained_by_the_intro_check() {
        UUID id = insertGeschichte("STORY", "<p>" + "x".repeat(4001) + "</p>");
        Integer count = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM geschichten WHERE id = ?", Integer.class, id);
        assertThat(count).isEqualTo(1);
    }
}
