package dev.lions.unionflow.server.security;

import dev.lions.unionflow.server.entity.Organisation;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.UUID;

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

/**
 * Tests unitaires pour {@link OrganisationContextHolder}.
 *
 * <p>Couvre la logique de résolution du contexte multi-organisation.
 */
@DisplayName("OrganisationContextHolder — logique du contexte multi-org")
class OrganisationContextHolderTest {

    @Test
    @DisplayName("hasContext: non résolu et orgId null → false")
    void hasContext_notResolvedAndNullOrgId_returnsFalse() {
        OrganisationContextHolder holder = new OrganisationContextHolder();
        assertThat(holder.hasContext()).isFalse();
    }

    @Test
    @DisplayName("hasContext: résolu mais orgId null → false")
    void hasContext_resolvedButNullOrgId_returnsFalse() {
        OrganisationContextHolder holder = new OrganisationContextHolder();
        holder.setResolved(true);
        holder.setOrganisationId(null);

        assertThat(holder.hasContext()).isFalse();
    }

    @Test
    @DisplayName("hasContext: orgId défini mais non résolu → false")
    void hasContext_orgIdSetButNotResolved_returnsFalse() {
        OrganisationContextHolder holder = new OrganisationContextHolder();
        holder.setOrganisationId(UUID.randomUUID());
        holder.setResolved(false);

        assertThat(holder.hasContext()).isFalse();
    }

    @Test
    @DisplayName("hasContext: résolu ET orgId défini → true")
    void hasContext_resolvedAndOrgIdSet_returnsTrue() {
        OrganisationContextHolder holder = new OrganisationContextHolder();
        holder.setOrganisationId(UUID.randomUUID());
        holder.setResolved(true);

        assertThat(holder.hasContext()).isTrue();
    }

    @Test
    @DisplayName("setOrganisation: organisation correctement stockée")
    void setOrganisation_storesCorrectly() {
        OrganisationContextHolder holder = new OrganisationContextHolder();
        Organisation org = new Organisation();
        UUID orgId = UUID.randomUUID();
        org.setId(orgId);
        org.setNom("Tontine Dakar");

        holder.setOrganisation(org);
        holder.setOrganisationId(orgId);
        holder.setResolved(true);

        assertThat(holder.getOrganisation()).isSameAs(org);
        assertThat(holder.getOrganisationId()).isEqualTo(orgId);
        assertThat(holder.isResolved()).isTrue();
        assertThat(holder.hasContext()).isTrue();
    }

    @Test
    @DisplayName("État initial: tous les champs sont null/false")
    void initialState_allFieldsAreDefault() {
        OrganisationContextHolder holder = new OrganisationContextHolder();

        assertThat(holder.getOrganisationId()).isNull();
        assertThat(holder.getOrganisation()).isNull();
        assertThat(holder.isResolved()).isFalse();
        assertThat(holder.hasContext()).isFalse();
    }
}
