1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
use crate::types::{ Contact, Links };
use reqwest::Client;
use serde::{ Deserialize, Serialize };
use validator::Validate;

use crate::{ constants::PROJECT_ENDPOINT, utils::apply_dotenv };

use validator::{ validate_email, validate_url };

use dialoguer::{ theme::ColorfulTheme, Input };

use color_eyre::eyre::eyre;

use serde_json::Value;

#[derive(Debug, Clone, Validate, Serialize, Deserialize)]
pub struct Project {
    #[validate(length(min = 1, max = 28))]
    pub name: String,
    #[validate]
    pub links: Links,
    #[validate]
    pub contact: Contact,
}

impl Project {
    #[must_use]
    pub fn new(
        name: String,
        twitter: Option<String>,
        github: Option<String>,
        website: Option<String>,
        email: Option<String>
    ) -> Self {
        Self {
            name,
            links: Links {
                twitter,
                github,
                website,
            },
            contact: Contact { email },
        }
    }

    pub async fn fetch_project_id(mut self, auth_token: &String) -> eyre::Result<String> {
        let client = Client::new();

        apply_dotenv()?;

        let project_endpoint = std::env
            ::var("PROJECT_ENDPOINT")
            .unwrap_or_else(|_| PROJECT_ENDPOINT.to_string());

        let project_name = self.clone().name;

        let mut response = client
            .get(&project_endpoint)
            .query(&[("query", project_name.as_str())])
            .send().await?;

        if !response.status().is_success() {
            return Err(eyre!("Error. Could not get project. Response: {:?}", response.status()));
        }

        let mut content = response.text().await?;

        let mut project_response_data: Value = serde_json::from_str(&content)?;

        let projects_found = &project_response_data.clone()["projectsFound"];

        if projects_found.is_null() {
            println!("Project not found. Creating project...");

            if self.links.website.is_none() {
                let project_website_url = Some(
                    Input::with_theme(&ColorfulTheme::default())
                        .with_prompt("Project Website URL")
                        .validate_with(|input: &String| {
                            if validate_url(input) { Ok(()) } else { Err(eyre!("Invalid link")) }
                        })
                        .interact_text()?
                );

                self.links.website = project_website_url;
            }

            if self.contact.email.is_none() {
                let project_contact = Some(
                    Input::with_theme(&ColorfulTheme::default())
                        .with_prompt("Project Contact Email")
                        .validate_with(|input: &String| {
                            if validate_email(input) { Ok(()) } else { Err(eyre!("Invalid Email")) }
                        })
                        .interact_text()?
                );

                self.contact.email = project_contact;
            }

            response = client
                .post(project_endpoint)
                .bearer_auth(auth_token)
                .json(&self)
                .send().await?;

            if !response.status().is_success() {
                return Err(
                    eyre!(
                        "Error. Could not create project. Response: {:?}\n Response Text: {:?}",
                        response.status(),
                        response.text().await?
                    )
                );
            }

            content = response.text().await?;

            project_response_data = serde_json::from_str(&content)?;

            let project_id = project_response_data["id"].to_string().trim().replace('\"', "");

            return Ok(project_id);
        }

        let projects_found = projects_found
            .as_array()
            .expect("cannot be reached. We only send an array");

        if projects_found.len().eq(&1) {
            return Ok(projects_found[0]["value"].to_string().trim().replace('\"', ""));
        }

        let project_id = projects_found
            .iter()
            .find(|project| project["label"].eq(&project_name))
            .and_then(|project| project["value"].as_str())
            .expect("cannot fail")
            .to_string()
            .trim()
            .replace('\"', "");

        println!("Project ID: {project_id}\n");

        Ok(project_id)
    }
}