use domain::models::UserRole;
use domain::value_objects::{Email, FollowTarget, SocialIdentity, UserId};

use crate::auth::commands::RegisterCommand;
use crate::auth::deps::RegisterDeps;
use crate::auth::register;
use crate::test_helpers::TestContextBuilder;
use crate::users::deps::GetPageViewerDeps;
use crate::users::get_page_viewer;

async fn setup_user(b: &TestContextBuilder, email: &str, username: &str) -> uuid::Uuid {
    let deps = RegisterDeps {
        user: b.user_repo.clone(),
        password_hasher: b.password_hasher.clone(),
        config: b.config.clone(),
    };
    register::execute(
        &deps,
        RegisterCommand {
            email: email.into(),
            username: username.into(),
            password: "password123".into(),
            role: UserRole::Standard,
        },
    )
    .await
    .unwrap();
    let user = b
        .user_repo
        .find_by_email(&Email::new(email.into()).unwrap())
        .await
        .unwrap()
        .unwrap();
    user.id().value()
}

/// `get_page_viewer` absorbs `helpers.rs::build_page_context`'s inline pending-count
/// computation. It must reuse `FollowGraphQuery::count_pending_followers` rather than
/// re-deriving the count from raw follow rows.
#[tokio::test]
async fn get_page_viewer_reports_pending_follower_count() {
    let b = TestContextBuilder::new();
    let owner_uuid = setup_user(&b, "owner@test.com", "pageowner").await;
    let follower1 = setup_user(&b, "follower1@test.com", "pagefollower1").await;
    let follower2 = setup_user(&b, "follower2@test.com", "pagefollower2").await;

    let owner_id = UserId::from_uuid(owner_uuid);
    let target = FollowTarget::Identity(SocialIdentity::Local(owner_id.clone()));
    b.social_command
        .follow(&UserId::from_uuid(follower1), &target)
        .await
        .unwrap();
    b.social_command
        .follow(&UserId::from_uuid(follower2), &target)
        .await
        .unwrap();

    let deps = GetPageViewerDeps {
        user: b.user_repo.clone(),
        follow_graph: b.social_query_unified.clone(),
    };

    let v = get_page_viewer::execute(&deps, owner_uuid).await.unwrap();
    assert_eq!(v.pending_follow_count, 2);
    assert!(!v.is_admin);
}
