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

use crate::types::error::{HorizonError, PostgresError, Result};
use crate::types::model::Ontology;

use super::PostgresRepository;

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

    /// Create an ontology.
    pub async fn insert_ontology(&self, ontology: &Ontology) -> Result<Ontology> {
        let now = Utc::now();
        let org = self.organization_id.or(ontology.organization_id);
        Ok(sqlx::query_as!(
            Ontology,
            r#"
            INSERT INTO horizon_public.ontology
                (id, name, description, organization_id, modified_datetime)
            VALUES (COALESCE($1, gen_random_uuid()), $2, $3, $4, $5)
            RETURNING id, created_datetime, modified_datetime,
                      name, description, organization_id
            "#,
            ontology.id,
            ontology.name,
            ontology.description,
            org,
            now,
        )
        .fetch_one(&self.pool)
        .await?)
    }

    /// List all ontology records.
    pub async fn list_ontologies(&self) -> Result<Vec<Ontology>> {
        Ok(sqlx::query_as!(
            Ontology,
            r#"
            SELECT id, created_datetime, modified_datetime,
                   name, description, organization_id
            FROM horizon_public.ontology
            "#,
        )
        .fetch_all(&self.pool)
        .await?)
    }

    /// Read an ontology by ID.
    pub async fn read_ontology(&self, id: Uuid) -> Result<Option<Ontology>> {
        Ok(sqlx::query_as!(
            Ontology,
            r#"
            SELECT id, created_datetime, modified_datetime,
                   name, description, organization_id
            FROM horizon_public.ontology WHERE id = $1
            "#,
            id,
        )
        .fetch_optional(&self.pool)
        .await?)
    }

    /// Update an existing ontology by ID.
    ///
    /// Returns `HorizonError::Postgres(PostgresError::NotFound)` if no row
    /// with the given ID exists. Matches Python `BaseRepository.update()`
    /// semantics.
    pub async fn update_ontology(&self, ontology: &Ontology) -> Result<Ontology> {
        let now = Utc::now();
        let org = self.organization_id.or(ontology.organization_id);
        let result = sqlx::query_as!(
            Ontology,
            r#"
            UPDATE horizon_public.ontology
            SET
                name = $2,
                description = $3,
                organization_id = $4,
                modified_datetime = $5
            WHERE id = $1
            RETURNING id, created_datetime, modified_datetime,
                      name, description, organization_id
            "#,
            ontology.id,
            ontology.name,
            ontology.description,
            org,
            now,
        )
        .fetch_optional(&self.pool)
        .await?;

        result.ok_or_else(|| {
            HorizonError::Postgres(PostgresError::NotFound {
                entity: "ontology".to_owned(),
                id: ontology.id.into(),
            })
        })
    }

    /// Insert an ontology or update it if a row with the same ID already
    /// exists. Sets `modified_datetime` to now and falls back to the
    /// repository's `organization_id` when the model does not provide one.
    pub async fn upsert_ontology(&self, ontology: &Ontology) -> Result<Ontology> {
        let now = Utc::now();
        let org = self.organization_id.or(ontology.organization_id);
        Ok(sqlx::query_as!(
            Ontology,
            r#"
            INSERT INTO horizon_public.ontology
                (id, name, description, organization_id, modified_datetime)
            VALUES (COALESCE($1, gen_random_uuid()), $2, $3, $4, $5)
            ON CONFLICT (id) DO UPDATE SET
                name = EXCLUDED.name, description = EXCLUDED.description,
                organization_id = EXCLUDED.organization_id,
                modified_datetime = EXCLUDED.modified_datetime
            RETURNING id, created_datetime, modified_datetime,
                      name, description, organization_id
            "#,
            ontology.id,
            ontology.name,
            ontology.description,
            org,
            now,
        )
        .fetch_one(&self.pool)
        .await?)
    }
}
