use chrono::Utc;
use uuid::Uuid;

use crate::postgres::retry::{RetryPolicy, retry};
use crate::types::error::Result;
use crate::types::model::PlatformKind;

use super::PostgresRepository;

impl PostgresRepository {
    /// Delete a platform kind by ID. Returns the number of rows removed.
    pub async fn delete_platform_kind(&self, id: Uuid) -> Result<u64> {
        let result = sqlx::query!("DELETE FROM horizon_public.platform_kind WHERE id = $1", id)
            .execute(&self.pool)
            .await?;
        Ok(result.rows_affected())
    }

    /// Create a new platform kind.
    pub async fn insert_platform_kind(&self, platform_kind: &PlatformKind) -> Result<PlatformKind> {
        let now = Utc::now();
        let org = self.organization_id.or(platform_kind.organization_id);
        Ok(sqlx::query_as!(
            PlatformKind,
            r#"
            INSERT INTO horizon_public.platform_kind
                (id, name, image_url, short_description, long_description,
                 organization_id, modified_datetime)
            VALUES (COALESCE($1, gen_random_uuid()), $2, $3, $4, $5, $6, $7)
            RETURNING id, created_datetime, modified_datetime, name, image_url,
                      short_description, long_description, organization_id
            "#,
            platform_kind.id,
            platform_kind.name,
            platform_kind.image_url,
            platform_kind.short_description,
            platform_kind.long_description,
            org,
            now,
        )
        .fetch_one(&self.pool)
        .await?)
    }

    /// List all platform kind records. Retried under the default [`RetryPolicy`] on
    /// transient Postgres errors; reads are naturally idempotent.
    pub async fn list_platform_kinds(&self) -> Result<Vec<PlatformKind>> {
        retry(RetryPolicy::default(), || async move {
            Ok(sqlx::query_as!(
                PlatformKind,
                r#"
                SELECT id, created_datetime, modified_datetime, name, image_url,
                       short_description, long_description, organization_id
                FROM horizon_public.platform_kind
                "#,
            )
            .fetch_all(&self.pool)
            .await?)
        })
        .await
    }

    /// Read a platform kind by ID. Retried under the default [`RetryPolicy`] on transient
    /// Postgres errors; reads are naturally idempotent.
    pub async fn read_platform_kind(&self, id: Uuid) -> Result<Option<PlatformKind>> {
        retry(RetryPolicy::default(), || async move {
            Ok(sqlx::query_as!(
                PlatformKind,
                r#"
                SELECT id, created_datetime, modified_datetime, name, image_url,
                       short_description, long_description, organization_id
                FROM horizon_public.platform_kind WHERE id = $1
                "#,
                id,
            )
            .fetch_optional(&self.pool)
            .await?)
        })
        .await
    }
}
