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

#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct GraphicDesignerProfile {
    pub id: Uuid,
    pub user_role_profile_id: Uuid,
    pub design_tools: Vec<String>,
    pub style_tags: Vec<String>,
    pub brand_experience: bool,
    pub starting_price_inr: Option<i32>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpsertGraphicDesignerProfilePayload {
    pub design_tools: Vec<String>,
    pub style_tags: Vec<String>,
    pub brand_experience: bool,
    pub starting_price_inr: Option<i32>,
}

pub struct GraphicDesignerRepository;

impl GraphicDesignerRepository {
    pub async fn get_by_user_id(pool: &PgPool, user_id: Uuid) -> Result<Option<GraphicDesignerProfile>, sqlx::Error> {
        sqlx::query_as::<_, GraphicDesignerProfile>(
            r#"SELECT gdp.id, gdp.user_role_profile_id, gdp.design_tools, gdp.style_tags,
                      gdp.brand_experience, gdp.starting_price_inr,
                      gdp.created_at, gdp.updated_at
               FROM graphic_designer_profiles gdp
               INNER JOIN user_role_profiles urp ON urp.id = gdp.user_role_profile_id
               WHERE urp.user_id = $1 AND urp.role_key = 'graphic_designer'"#,
        )
        .bind(user_id)
        .fetch_optional(pool)
        .await
    }

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

        sqlx::query_as::<_, GraphicDesignerProfile>(
            r#"INSERT INTO graphic_designer_profiles (user_role_profile_id, design_tools, style_tags,
                                                     brand_experience, starting_price_inr)
               VALUES ($1, $2, $3, $4, $5)
               ON CONFLICT (user_role_profile_id) DO UPDATE SET
                   design_tools = COALESCE(EXCLUDED.design_tools, graphic_designer_profiles.design_tools),
                   style_tags = COALESCE(EXCLUDED.style_tags, graphic_designer_profiles.style_tags),
                   brand_experience = EXCLUDED.brand_experience,
                   starting_price_inr = EXCLUDED.starting_price_inr,
                   updated_at = NOW()
               RETURNING id, user_role_profile_id, design_tools, style_tags, brand_experience,
                         starting_price_inr, created_at, updated_at"#,
        )
        .bind(user_role_profile.0)
        .bind(&p.design_tools)
        .bind(&p.style_tags)
        .bind(p.brand_experience)
        .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<GraphicDesignerProfile>, sqlx::Error> {
        sqlx::query_as::<_, GraphicDesignerProfile>(
            r#"SELECT id, user_role_profile_id, design_tools, style_tags, brand_experience,
                      starting_price_inr, created_at, updated_at
               FROM graphic_designer_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: UpsertGraphicDesignerProfilePayload) -> Result<GraphicDesignerProfile, sqlx::Error> {
        sqlx::query_as::<_, GraphicDesignerProfile>(
            r#"INSERT INTO graphic_designer_profiles (user_role_profile_id, design_tools, style_tags,
                                                    brand_experience, starting_price_inr)
               VALUES ($1, $2, $3, $4, $5)
               ON CONFLICT (user_role_profile_id) DO UPDATE SET
                   design_tools = COALESCE(EXCLUDED.design_tools, graphic_designer_profiles.design_tools),
                   style_tags = COALESCE(EXCLUDED.style_tags, graphic_designer_profiles.style_tags),
                   brand_experience = EXCLUDED.brand_experience,
                   starting_price_inr = EXCLUDED.starting_price_inr,
                   updated_at = NOW()
               RETURNING id, user_role_profile_id, design_tools, style_tags, brand_experience,
                         starting_price_inr, created_at, updated_at"#,
        )
        .bind(user_role_profile_id)
        .bind(&p.design_tools)
        .bind(&p.style_tags)
        .bind(p.brand_experience)
        .bind(p.starting_price_inr)
        .fetch_one(pool)
        .await
    }
}
