use chrono::Utc;

use crate::types::error::Result;
use crate::types::model::PlatformInformation;

use super::PostgresRepository;

impl PostgresRepository {
    /// Create a new platform information record.
    pub async fn insert_platform_information(
        &self,
        pi: &PlatformInformation,
    ) -> Result<PlatformInformation> {
        let now = Utc::now();
        let org = self.organization_id.or(pi.organization_id);
        Ok(sqlx::query_as!(
            PlatformInformation,
            r#"
            INSERT INTO horizon_public.platform_information
                (id, platform_id, organization_id, properties, modified_datetime)
            VALUES (COALESCE($1, gen_random_uuid()), $2, $3, $4, $5)
            RETURNING id, created_datetime, modified_datetime,
                      platform_id, organization_id, properties
            "#,
            pi.id,
            pi.platform_id,
            org,
            pi.properties,
            now,
        )
        .fetch_one(&self.pool)
        .await?)
    }

    /// List all platform information record records.
    pub async fn list_platform_information(&self) -> Result<Vec<PlatformInformation>> {
        Ok(sqlx::query_as!(
            PlatformInformation,
            r#"
            SELECT id, created_datetime, modified_datetime,
                   platform_id, organization_id, properties
            FROM horizon_public.platform_information
            "#,
        )
        .fetch_all(&self.pool)
        .await?)
    }
}
