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

#[derive(Debug, Serialize, Deserialize, FromRow)]
pub struct PhotographerProfile {
    pub id: Uuid,
    pub user_role_profile_id: Uuid,
    pub specialties: Vec<String>,
    pub camera_brands: Vec<String>,
    pub studio_available: bool,
    pub outdoor_shoots: bool,
    pub travel_radius_km: Option<i32>,
    pub starting_price_inr: Option<i32>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct UpsertPhotographerProfilePayload {
    pub specialties: Vec<String>,
    pub camera_brands: Vec<String>,
    pub studio_available: bool,
    pub outdoor_shoots: bool,
    pub travel_radius_km: Option<i32>,
    pub starting_price_inr: Option<i32>,
}

pub struct PhotographerRepository;

impl PhotographerRepository {
    pub async fn get_by_user_id(pool: &PgPool, user_id: Uuid) -> Result<Option<PhotographerProfile>, sqlx::Error> {
        sqlx::query_as::<_, PhotographerProfile>(
            r#"SELECT pp.id, pp.user_role_profile_id, pp.specialties, pp.camera_brands,
                      pp.studio_available, pp.outdoor_shoots, pp.travel_radius_km,
                      pp.starting_price_inr,
                      pp.created_at, pp.updated_at
               FROM photographer_profiles pp
               INNER JOIN user_role_profiles urp ON urp.id = pp.user_role_profile_id
               WHERE urp.user_id = $1 AND urp.role_key = 'PHOTOGRAPHER'"#,
        )
        .bind(user_id)
        .fetch_optional(pool)
        .await
    }

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

        sqlx::query_as::<_, PhotographerProfile>(
            r#"INSERT INTO photographer_profiles (user_role_profile_id, specialties, camera_brands,
                                                 studio_available, outdoor_shoots, travel_radius_km, starting_price_inr)
               VALUES ($1, $2, $3, $4, $5, $6, $7)
               ON CONFLICT (user_role_profile_id) DO UPDATE SET
                   specialties = COALESCE(EXCLUDED.specialties, photographer_profiles.specialties),
                   camera_brands = COALESCE(EXCLUDED.camera_brands, photographer_profiles.camera_brands),
                   studio_available = EXCLUDED.studio_available,
                   outdoor_shoots = EXCLUDED.outdoor_shoots,
                   travel_radius_km = EXCLUDED.travel_radius_km,
                   starting_price_inr = EXCLUDED.starting_price_inr,
                   updated_at = NOW()
               RETURNING id, user_role_profile_id, specialties, camera_brands,
                         studio_available, outdoor_shoots, travel_radius_km,
                         starting_price_inr, created_at, updated_at"#,
        )
        .bind(user_role_profile.0)
        .bind(&p.specialties)
        .bind(&p.camera_brands)
        .bind(p.studio_available)
        .bind(p.outdoor_shoots)
        .bind(p.travel_radius_km)
        .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<PhotographerProfile>, sqlx::Error> {
        sqlx::query_as::<_, PhotographerProfile>(
            r#"SELECT id, user_role_profile_id, specialties, camera_brands,
                      studio_available, outdoor_shoots, travel_radius_km,
                      starting_price_inr,
                      created_at, updated_at
               FROM photographer_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: UpsertPhotographerProfilePayload) -> Result<PhotographerProfile, sqlx::Error> {
        sqlx::query_as::<_, PhotographerProfile>(
            r#"INSERT INTO photographer_profiles (user_role_profile_id, specialties, camera_brands,
                                                 studio_available, outdoor_shoots, travel_radius_km, starting_price_inr)
               VALUES ($1, $2, $3, $4, $5, $6, $7)
               ON CONFLICT (user_role_profile_id) DO UPDATE SET
                   specialties = COALESCE(EXCLUDED.specialties, photographer_profiles.specialties),
                   camera_brands = COALESCE(EXCLUDED.camera_brands, photographer_profiles.camera_brands),
                   studio_available = EXCLUDED.studio_available,
                   outdoor_shoots = EXCLUDED.outdoor_shoots,
                   travel_radius_km = EXCLUDED.travel_radius_km,
                   starting_price_inr = EXCLUDED.starting_price_inr,
                   updated_at = NOW()
               RETURNING id, user_role_profile_id, specialties, camera_brands,
                         studio_available, outdoor_shoots, travel_radius_km,
                         starting_price_inr, created_at, updated_at"#,
        )
        .bind(user_role_profile_id)
        .bind(&p.specialties)
        .bind(&p.camera_brands)
        .bind(p.studio_available)
        .bind(p.outdoor_shoots)
        .bind(p.travel_radius_km)
        .bind(p.starting_price_inr)
        .fetch_one(pool)
        .await
    }
}
