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

#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct DeveloperProfile {
    pub id: Uuid,
    pub user_role_profile_id: Uuid,
    pub tech_stack: Vec<String>,
    pub experience_years: Option<i32>,
    pub availability: String,
    pub hourly_rate_inr: Option<i32>,
    pub remote_ok: bool,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpsertDeveloperProfilePayload {
    pub tech_stack: Vec<String>,
    pub experience_years: Option<i32>,
    pub availability: String,
    pub hourly_rate_inr: Option<i32>,
    pub remote_ok: bool,
}

pub struct DeveloperRepository;

impl DeveloperRepository {
    pub async fn get_by_user_id(pool: &PgPool, user_id: Uuid) -> Result<Option<DeveloperProfile>, sqlx::Error> {
        sqlx::query_as::<_, DeveloperProfile>(
            r#"SELECT dp.id, dp.user_role_profile_id, dp.tech_stack, dp.experience_years, dp.availability,
                      dp.hourly_rate_inr, dp.remote_ok,
                      dp.created_at, dp.updated_at
               FROM developer_profiles dp
               INNER JOIN user_role_profiles urp ON urp.id = dp.user_role_profile_id
               WHERE urp.user_id = $1 AND urp.role_key = 'developer'"#,
        )
        .bind(user_id)
        .fetch_optional(pool)
        .await
    }

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

        sqlx::query_as::<_, DeveloperProfile>(
            r#"INSERT INTO developer_profiles (user_role_profile_id, tech_stack, experience_years,
                                             availability, hourly_rate_inr, remote_ok)
               VALUES ($1, $2, $3, $4, $5, $6)
               ON CONFLICT (user_role_profile_id) DO UPDATE SET
                   tech_stack = COALESCE(EXCLUDED.tech_stack, developer_profiles.tech_stack),
                   experience_years = EXCLUDED.experience_years,
                   availability = EXCLUDED.availability,
                   hourly_rate_inr = EXCLUDED.hourly_rate_inr,
                   remote_ok = EXCLUDED.remote_ok,
                   updated_at = NOW()
               RETURNING id, user_role_profile_id, tech_stack, experience_years, availability,
                         hourly_rate_inr, remote_ok, created_at, updated_at"#,
        )
        .bind(user_role_profile.0)
        .bind(&p.tech_stack)
        .bind(p.experience_years)
        .bind(&p.availability)
        .bind(p.hourly_rate_inr)
        .bind(p.remote_ok)
        .fetch_one(pool)
        .await
    }

    pub async fn get_by_user_role_id(pool: &PgPool, user_role_profile_id: Uuid) -> Result<Option<DeveloperProfile>, sqlx::Error> {
        sqlx::query_as::<_, DeveloperProfile>(
            r#"SELECT id, user_role_profile_id, tech_stack, experience_years, availability,
                      hourly_rate_inr, remote_ok, created_at, updated_at
               FROM developer_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: UpsertDeveloperProfilePayload) -> Result<DeveloperProfile, sqlx::Error> {
        sqlx::query_as::<_, DeveloperProfile>(
            r#"INSERT INTO developer_profiles (user_role_profile_id, tech_stack, experience_years,
                                             availability, hourly_rate_inr, remote_ok)
               VALUES ($1, $2, $3, $4, $5, $6)
               ON CONFLICT (user_role_profile_id) DO UPDATE SET
                   tech_stack = COALESCE(EXCLUDED.tech_stack, developer_profiles.tech_stack),
                   experience_years = EXCLUDED.experience_years,
                   availability = EXCLUDED.availability,
                   hourly_rate_inr = EXCLUDED.hourly_rate_inr,
                   remote_ok = EXCLUDED.remote_ok,
                   updated_at = NOW()
               RETURNING id, user_role_profile_id, tech_stack, experience_years, availability,
                         hourly_rate_inr, remote_ok, created_at, updated_at"#,
        )
        .bind(user_role_profile_id)
        .bind(&p.tech_stack)
        .bind(p.experience_years)
        .bind(&p.availability)
        .bind(p.hourly_rate_inr)
        .bind(p.remote_ok)
        .fetch_one(pool)
        .await
    }
}
