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

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

use super::PostgresRepository;

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

    /// Create a new directional spectrogram specification.
    pub async fn insert_directional_spectrogram_specification(
        &self,
        spec: &DirectionalSpectrogramSpecification,
    ) -> Result<DirectionalSpectrogramSpecification> {
        let now = Utc::now();
        let org = self.organization_id.or(spec.organization_id);
        Ok(sqlx::query_as!(
            DirectionalSpectrogramSpecification,
            r#"
            INSERT INTO horizon_public.directional_spectrogram_specification
                (id, bearing_leading_rows, bearing_lagging_rows, spectrogram_specification_id, organization_id, modified_datetime)
            VALUES (COALESCE($1, gen_random_uuid()), $2, $3, $4, $5, $6)
            RETURNING id, created_datetime, modified_datetime,
                      bearing_leading_rows, bearing_lagging_rows, spectrogram_specification_id, organization_id
            "#,
            spec.id,
            spec.bearing_leading_rows,
            spec.bearing_lagging_rows,
            spec.spectrogram_specification_id,
            org,
            now,
        )
        .fetch_one(&self.pool)
        .await?)
    }

    /// List all directional spectrogram specification records.
    pub async fn list_directional_spectrogram_specifications(
        &self,
    ) -> Result<Vec<DirectionalSpectrogramSpecification>> {
        Ok(sqlx::query_as!(
            DirectionalSpectrogramSpecification,
            r#"
            SELECT id, created_datetime, modified_datetime,
                   bearing_leading_rows, bearing_lagging_rows, spectrogram_specification_id, organization_id
            FROM horizon_public.directional_spectrogram_specification
            "#,
        )
        .fetch_all(&self.pool)
        .await?)
    }

    /// Read a directional spectrogram specification by ID.
    pub async fn read_directional_spectrogram_specification(
        &self,
        id: Uuid,
    ) -> Result<Option<DirectionalSpectrogramSpecification>> {
        Ok(sqlx::query_as!(
            DirectionalSpectrogramSpecification,
            r#"
            SELECT id, created_datetime, modified_datetime,
                   bearing_leading_rows, bearing_lagging_rows, spectrogram_specification_id, organization_id
            FROM horizon_public.directional_spectrogram_specification WHERE id = $1
            "#,
            id,
        )
        .fetch_optional(&self.pool)
        .await?)
    }

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

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

    /// Insert a directional spectrogram specification 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_directional_spectrogram_specification(
        &self,
        spec: &DirectionalSpectrogramSpecification,
    ) -> Result<DirectionalSpectrogramSpecification> {
        let now = Utc::now();
        let org = self.organization_id.or(spec.organization_id);
        Ok(sqlx::query_as!(
            DirectionalSpectrogramSpecification,
            r#"
            INSERT INTO horizon_public.directional_spectrogram_specification
                (id, bearing_leading_rows, bearing_lagging_rows, spectrogram_specification_id, organization_id, modified_datetime)
            VALUES (COALESCE($1, gen_random_uuid()), $2, $3, $4, $5, $6)
            ON CONFLICT (id) DO UPDATE SET
                bearing_leading_rows = EXCLUDED.bearing_leading_rows,
                bearing_lagging_rows = EXCLUDED.bearing_lagging_rows,
                spectrogram_specification_id = EXCLUDED.spectrogram_specification_id,
                organization_id = EXCLUDED.organization_id,
                modified_datetime = EXCLUDED.modified_datetime
            RETURNING id, created_datetime, modified_datetime,
                      bearing_leading_rows, bearing_lagging_rows, spectrogram_specification_id, organization_id
            "#,
            spec.id,
            spec.bearing_leading_rows,
            spec.bearing_lagging_rows,
            spec.spectrogram_specification_id,
            org,
            now,
        )
        .fetch_one(&self.pool)
        .await?)
    }
}
