use common_contracts::dtos::CompanyProfileDto;
use common_contracts::models::CompanyProfile;
use sqlx::PgPool;

pub async fn upsert_company(pool: &PgPool, payload: &CompanyProfileDto) -> Result<(), sqlx::Error> {
    sqlx::query(
        r#"
        INSERT INTO company_profiles (symbol, name, industry, list_date, additional_info, updated_at)
        VALUES ($1, $2, $3, $4, $5, NOW())
        ON CONFLICT (symbol) DO UPDATE SET
            name = EXCLUDED.name,
            industry = EXCLUDED.industry,
            list_date = EXCLUDED.list_date,
            additional_info = EXCLUDED.additional_info,
            updated_at = NOW()
        "#,
    )
    .bind(&payload.symbol)
    .bind(&payload.name)
    .bind(&payload.industry)
    .bind(&payload.list_date)
    .bind(&payload.additional_info)
    .execute(pool)
    .await?;
    Ok(())
}

pub async fn get_company_by_symbol(pool: &PgPool, symbol: &str) -> Result<Option<CompanyProfile>, sqlx::Error> {
    let rec = sqlx::query_as::<_, CompanyProfile>(
        r#"
        SELECT symbol, name, industry, list_date, additional_info, updated_at
        FROM company_profiles
        WHERE symbol = $1
        "#,
    )
    .bind(symbol)
    .fetch_optional(pool)
    .await?;
    Ok(rec)
}


