use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, PgPool};
use uuid::Uuid;

#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct MakeupArtistProfile {
    pub id: Uuid,
    pub user_role_profile_id: Uuid,
    pub specializations: Vec<String>,
    pub kit_brands: Vec<String>,
    pub home_service: bool,
    pub studio_available: bool,
    pub starting_price_inr: Option<i32>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpsertMakeupArtistProfilePayload {
    pub specializations: Vec<String>,
    pub kit_brands: Vec<String>,
    pub home_service: bool,
    pub studio_available: bool,
    pub starting_price_inr: Option<i32>,
}

pub struct MakeupArtistRepository;

impl MakeupArtistRepository {
    pub async fn get_by_user_id(pool: &PgPool, user_id: Uuid) -> Result<Option<MakeupArtistProfile>, sqlx::Error> {
        sqlx::query_as::<_, MakeupArtistProfile>(
            r#"SELECT map.id, map.user_role_profile_id, map.specializations, map.kit_brands,
                      map.home_service, map.studio_available, map.starting_price_inr,
                      map.created_at, map.updated_at
               FROM makeup_artist_profiles map
               INNER JOIN user_role_profiles urp ON urp.id = map.user_role_profile_id
               WHERE urp.user_id = $1 AND urp.role_key = 'makeup_artist'"#,
        )
        .bind(user_id)
        .fetch_optional(pool)
        .await
    }

    pub async fn upsert_by_user_id(pool: &PgPool, user_id: Uuid, p: UpsertMakeupArtistProfilePayload) -> Result<MakeupArtistProfile, sqlx::Error> {
        let user_role_profile = sqlx::query_as::<_, (Uuid,)>(
            r#"SELECT id FROM user_role_profiles WHERE user_id = $1 AND role_key = 'makeup_artist'"#,
        )
        .bind(user_id)
        .fetch_optional(pool)
        .await?
        .ok_or(sqlx::Error::RowNotFound)?;

        sqlx::query_as::<_, MakeupArtistProfile>(
            r#"INSERT INTO makeup_artist_profiles (user_role_profile_id, specializations, kit_brands,
                                                 home_service, studio_available, starting_price_inr)
               VALUES ($1, $2, $3, $4, $5, $6)
               ON CONFLICT (user_role_profile_id) DO UPDATE SET
                   specializations = COALESCE(EXCLUDED.specializations, makeup_artist_profiles.specializations),
                   kit_brands = COALESCE(EXCLUDED.kit_brands, makeup_artist_profiles.kit_brands),
                   home_service = EXCLUDED.home_service,
                   studio_available = EXCLUDED.studio_available,
                   starting_price_inr = EXCLUDED.starting_price_inr,
                   updated_at = NOW()
               RETURNING id, user_role_profile_id, specializations, kit_brands,
                         home_service, studio_available, starting_price_inr,
                         created_at, updated_at"#,
        )
        .bind(user_role_profile.0)
        .bind(&p.specializations)
        .bind(&p.kit_brands)
        .bind(p.home_service)
        .bind(p.studio_available)
        .bind(p.starting_price_inr)
        .fetch_one(pool)
        .await
    }

    pub async fn get_by_user_role_id(pool: &PgPool, user_role_profile_id: Uuid) -> Result<Option<MakeupArtistProfile>, sqlx::Error> {
        sqlx::query_as::<_, MakeupArtistProfile>(
            r#"SELECT id, user_role_profile_id, specializations, kit_brands,
                      home_service, studio_available, starting_price_inr,
                      created_at, updated_at
               FROM makeup_artist_profiles WHERE user_role_profile_id = $1"#,
        )
        .bind(user_role_profile_id)
        .fetch_optional(pool)
        .await
    }

    pub async fn upsert(pool: &PgPool, user_role_profile_id: Uuid, p: UpsertMakeupArtistProfilePayload) -> Result<MakeupArtistProfile, sqlx::Error> {
        sqlx::query_as::<_, MakeupArtistProfile>(
            r#"INSERT INTO makeup_artist_profiles (user_role_profile_id, specializations, kit_brands,
                                                 home_service, studio_available, starting_price_inr)
               VALUES ($1, $2, $3, $4, $5, $6)
               ON CONFLICT (user_role_profile_id) DO UPDATE SET
                   specializations = COALESCE(EXCLUDED.specializations, makeup_artist_profiles.specializations),
                   kit_brands = COALESCE(EXCLUDED.kit_brands, makeup_artist_profiles.kit_brands),
                   home_service = EXCLUDED.home_service,
                   studio_available = EXCLUDED.studio_available,
                   starting_price_inr = EXCLUDED.starting_price_inr,
                   updated_at = NOW()
               RETURNING id, user_role_profile_id, specializations, kit_brands,
                         home_service, studio_available, starting_price_inr,
                         created_at, updated_at"#,
        )
        .bind(user_role_profile_id)
        .bind(&p.specializations)
        .bind(&p.kit_brands)
        .bind(p.home_service)
        .bind(p.studio_available)
        .bind(p.starting_price_inr)
        .fetch_one(pool)
        .await
    }
}
