use actix_web::{HttpRequest, HttpResponse, web};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::{AppState, account::AccountRepository, auth::User, error::Result};

#[derive(Debug, Serialize, Deserialize)]
pub struct Repository {
    pub id: u64,
    pub name: String,
    pub full_name: String,
    pub description: Option<String>,
    pub language: Option<String>,
    #[serde(alias = "stargazers_count")]
    pub stars: Option<usize>,
    pub updated_at: DateTime<Utc>,
    pub private: bool,
}

pub async fn get_repos(
    app_state: web::Data<AppState>,
    req: web::ReqData<User>,
) -> Result<HttpResponse> {
    let user = req.into_inner();
    let query = AccountRepository::new(&app_state.pool);
    let token = query.get_access_token(&user.id).await?;

    let response = app_state
        .reqwest_client
        .get("https://api.github.com/user/repos?affiliation=owner&sort=updated&direction=desc&per_page=5")
        .bearer_auth(token)
        .send()
        .await?;
    response.error_for_status_ref()?;
    let data = response
        .json::<Vec<Repository>>()
        .await?
        .into_iter()
        .filter(|r| r.private == false)
        .collect::<Vec<Repository>>();

    Ok(HttpResponse::Ok().json(data))
}
