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

#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct SocialMediaManagerProfile {
    pub id: Uuid,
    pub user_role_profile_id: Uuid,
    pub platforms: Vec<String>,
    pub industries: Vec<String>,
    pub content_types: Vec<String>,
    pub avg_follower_growth_pct: Option<i32>,
    pub starting_price_inr: Option<i32>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpsertSocialMediaManagerProfilePayload {
    pub platforms: Vec<String>,
    pub industries: Vec<String>,
    pub content_types: Vec<String>,
    pub avg_follower_growth_pct: Option<i32>,
    pub starting_price_inr: Option<i32>,
}

pub struct SocialMediaManagerRepository;

impl SocialMediaManagerRepository {
    pub async fn get_by_user_id(pool: &PgPool, user_id: Uuid) -> Result<Option<SocialMediaManagerProfile>, sqlx::Error> {
        sqlx::query_as::<_, SocialMediaManagerProfile>(
            r#"SELECT smmp.id, smmp.user_role_profile_id, smmp.platforms, smmp.industries, smmp.content_types,
                      smmp.avg_follower_growth_pct, smmp.starting_price_inr,
                      smmp.created_at, smmp.updated_at
               FROM social_media_manager_profiles smmp
               INNER JOIN user_role_profiles urp ON urp.id = smmp.user_role_profile_id
               WHERE urp.user_id = $1 AND urp.role_key = 'social_media_manager'"#,
        )
        .bind(user_id)
        .fetch_optional(pool)
        .await
    }

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

        sqlx::query_as::<_, SocialMediaManagerProfile>(
            r#"INSERT INTO social_media_manager_profiles (user_role_profile_id, platforms, industries,
                                                       content_types, avg_follower_growth_pct, starting_price_inr)
               VALUES ($1, $2, $3, $4, $5, $6)
               ON CONFLICT (user_role_profile_id) DO UPDATE SET
                   platforms = COALESCE(EXCLUDED.platforms, social_media_manager_profiles.platforms),
                   industries = COALESCE(EXCLUDED.industries, social_media_manager_profiles.industries),
                   content_types = COALESCE(EXCLUDED.content_types, social_media_manager_profiles.content_types),
                   avg_follower_growth_pct = EXCLUDED.avg_follower_growth_pct,
                   starting_price_inr = EXCLUDED.starting_price_inr,
                   updated_at = NOW()
               RETURNING id, user_role_profile_id, platforms, industries, content_types,
                         avg_follower_growth_pct, starting_price_inr, created_at, updated_at"#,
        )
        .bind(user_role_profile.0)
        .bind(&p.platforms)
        .bind(&p.industries)
        .bind(&p.content_types)
        .bind(p.avg_follower_growth_pct)
        .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<SocialMediaManagerProfile>, sqlx::Error> {
        sqlx::query_as::<_, SocialMediaManagerProfile>(
            r#"SELECT id, user_role_profile_id, platforms, industries, content_types,
                      avg_follower_growth_pct, starting_price_inr, created_at, updated_at
               FROM social_media_manager_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: UpsertSocialMediaManagerProfilePayload) -> Result<SocialMediaManagerProfile, sqlx::Error> {
        sqlx::query_as::<_, SocialMediaManagerProfile>(
            r#"INSERT INTO social_media_manager_profiles (user_role_profile_id, platforms, industries,
                                                       content_types, avg_follower_growth_pct, starting_price_inr)
               VALUES ($1, $2, $3, $4, $5, $6)
               ON CONFLICT (user_role_profile_id) DO UPDATE SET
                   platforms = COALESCE(EXCLUDED.platforms, social_media_manager_profiles.platforms),
                   industries = COALESCE(EXCLUDED.industries, social_media_manager_profiles.industries),
                   content_types = COALESCE(EXCLUDED.content_types, social_media_manager_profiles.content_types),
                   avg_follower_growth_pct = EXCLUDED.avg_follower_growth_pct,
                   starting_price_inr = EXCLUDED.starting_price_inr,
                   updated_at = NOW()
               RETURNING id, user_role_profile_id, platforms, industries, content_types,
                         avg_follower_growth_pct, starting_price_inr, created_at, updated_at"#,
        )
        .bind(user_role_profile_id)
        .bind(&p.platforms)
        .bind(&p.industries)
        .bind(&p.content_types)
        .bind(p.avg_follower_growth_pct)
        .bind(p.starting_price_inr)
        .fetch_one(pool)
        .await
    }
}
