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

#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct VideoEditorProfile {
    pub id: Uuid,
    pub user_role_profile_id: Uuid,
    pub software_skills: Vec<String>,
    pub style_tags: Vec<String>,
    pub turnaround_days: 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 UpsertVideoEditorProfilePayload {
    pub software_skills: Vec<String>,
    pub style_tags: Vec<String>,
    pub turnaround_days: Option<i32>,
    pub starting_price_inr: Option<i32>,
}

pub struct VideoEditorRepository;

impl VideoEditorRepository {
    pub async fn get_by_user_id(pool: &PgPool, user_id: Uuid) -> Result<Option<VideoEditorProfile>, sqlx::Error> {
        sqlx::query_as::<_, VideoEditorProfile>(
            r#"SELECT vep.id, vep.user_role_profile_id, vep.software_skills, vep.style_tags,
                      vep.turnaround_days, vep.starting_price_inr,
                      vep.created_at, vep.updated_at
               FROM video_editor_profiles vep
               INNER JOIN user_role_profiles urp ON urp.id = vep.user_role_profile_id
               WHERE urp.user_id = $1 AND urp.role_key = 'video_editor'"#,
        )
        .bind(user_id)
        .fetch_optional(pool)
        .await
    }

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

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