use crate::{Backend, random_names::get_name_by_uuid};
use serde::{Deserialize, Serialize};
use sqlx::FromRow;
use uuid::Uuid;

#[derive(FromRow, Debug, Serialize, Deserialize)]
pub struct Client {
    pub uuid: String,
    pub name: Option<String>,
}

impl PartialEq for Client {
    fn eq(&self, other: &Self) -> bool {
        self.uuid == other.uuid
    }
}

impl Client {
    pub(crate) fn get_display_name(&self) -> String {
        match &self.name {
            Some(name) => name.to_string(),
            None => get_name_by_uuid(&self.uuid).to_string(),
        }
    }
}

impl Backend {
    pub(crate) async fn get_client(&self, uuid: &Uuid) -> Client {
        let uuid = uuid.to_string();

        match self {
            Backend::Sqlite(db) => {
                sqlx::query!("INSERT OR IGNORE INTO client (uuid) VALUES (?);", uuid)
                    .execute(db)
                    .await
                    .unwrap();
                sqlx::query_as!(Client, "SELECT uuid, name FROM client WHERE uuid = ?", uuid)
                    .fetch_one(db)
                    .await
                    .expect("we assured that uuid exists in previous query")
            }
        }
    }

    pub(crate) async fn delete_client_data(&self, uuid: &Uuid) -> Result<(), sqlx::Error> {
        let uuid_str = uuid.to_string();

        match self {
            Backend::Sqlite(db) => {
                // Start a transaction to ensure data consistency
                let mut tx = db.begin().await?;
                
                // Delete sightings first (foreign key constraint)
                sqlx::query!("DELETE FROM sightings WHERE client_uuid = ?", uuid_str)
                    .execute(&mut *tx)
                    .await?;
                
                // Delete client record
                sqlx::query!("DELETE FROM client WHERE uuid = ?", uuid_str)
                    .execute(&mut *tx)
                    .await?;
                
                tx.commit().await?;
                Ok(())
            }
        }
    }
}
