use crate::{auth::User, endpoints::get_repos::Repository, error::Result};
use actix_web::{
    HttpResponse,
    web::{self, ReqData},
};
use serde::{Deserialize, Serialize};

use crate::AppState;

#[derive(Deserialize)]
pub(crate) struct SearchQuery {
    q: String,
}

#[derive(Serialize, Deserialize)]
struct SearchResponse {
    items: Vec<Repository>,
}

pub async fn search_repos(
    app_state: web::Data<AppState>,
    query: web::Query<SearchQuery>,
    user: ReqData<User>,
) -> Result<HttpResponse> {
    let token = app_state.user.get_access_token(&user.id).await?;

    let search_query = format!("user:{} {} fork:true", user.name, query.q);
    let response = app_state
        .reqwest_client
        .get("https://api.github.com/search/repositories")
        .query(&[("q", &search_query)])
        .bearer_auth(&token)
        .send()
        .await?
        .json::<SearchResponse>()
        .await?;

    Ok(HttpResponse::Ok().json(response.items))
}
