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

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

use super::PostgresRepository;

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

    /// Create a new spectrogram specification.
    pub async fn insert_spectrogram_specification(
        &self,
        spec: &SpectrogramSpecification,
    ) -> Result<SpectrogramSpecification> {
        let now = Utc::now();
        let org = self.organization_id.or(spec.organization_id);
        Ok(sqlx::query_as!(
            SpectrogramSpecification,
            r#"
            INSERT INTO horizon_public.spectrogram_specification
                (id, amplitude_unit_mode, channel, frequency_spacing, name,
                 fft_sample_count, fft_sample_overlap_count,
                 organization_id, channel_role, modified_datetime)
            VALUES (COALESCE($1, gen_random_uuid()), $2, $3, $4, $5, $6, $7, $8, $9, $10)
            RETURNING id, amplitude_unit_mode, created_datetime, modified_datetime, channel,
                      frequency_spacing, name, fft_sample_count, fft_sample_overlap_count,
                      organization_id, channel_role
            "#,
            spec.id,
            spec.amplitude_unit_mode,
            spec.channel,
            spec.frequency_spacing,
            spec.name,
            spec.fft_sample_count,
            spec.fft_sample_overlap_count,
            org,
            spec.channel_role,
            now,
        )
        .fetch_one(&self.pool)
        .await?)
    }

    /// List all spectrogram specification records.
    pub async fn list_spectrogram_specifications(&self) -> Result<Vec<SpectrogramSpecification>> {
        Ok(sqlx::query_as!(
            SpectrogramSpecification,
            r#"
            SELECT id, amplitude_unit_mode, created_datetime, modified_datetime, channel,
                   frequency_spacing, name, fft_sample_count, fft_sample_overlap_count,
                   organization_id, channel_role
            FROM horizon_public.spectrogram_specification
            "#,
        )
        .fetch_all(&self.pool)
        .await?)
    }

    /// Read a spectrogram specification by ID.
    pub async fn read_spectrogram_specification(
        &self,
        id: Uuid,
    ) -> Result<Option<SpectrogramSpecification>> {
        Ok(sqlx::query_as!(
            SpectrogramSpecification,
            r#"
            SELECT id, amplitude_unit_mode, created_datetime, modified_datetime, channel,
                   frequency_spacing, name, fft_sample_count, fft_sample_overlap_count,
                   organization_id, channel_role
            FROM horizon_public.spectrogram_specification WHERE id = $1
            "#,
            id,
        )
        .fetch_optional(&self.pool)
        .await?)
    }

    /// Update an existing 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_spectrogram_specification(
        &self,
        spec: &SpectrogramSpecification,
    ) -> Result<SpectrogramSpecification> {
        let now = Utc::now();
        let org = self.organization_id.or(spec.organization_id);
        let result = sqlx::query_as!(
            SpectrogramSpecification,
            r#"
            UPDATE horizon_public.spectrogram_specification
            SET
                amplitude_unit_mode = $2,
                channel = $3,
                frequency_spacing = $4,
                name = $5,
                fft_sample_count = $6,
                fft_sample_overlap_count = $7,
                organization_id = $8,
                channel_role = $9,
                modified_datetime = $10
            WHERE id = $1
            RETURNING id, amplitude_unit_mode, created_datetime, modified_datetime, channel,
                      frequency_spacing, name, fft_sample_count, fft_sample_overlap_count,
                      organization_id, channel_role
            "#,
            spec.id,
            spec.amplitude_unit_mode,
            spec.channel,
            spec.frequency_spacing,
            spec.name,
            spec.fft_sample_count,
            spec.fft_sample_overlap_count,
            org,
            spec.channel_role,
            now,
        )
        .fetch_optional(&self.pool)
        .await?;

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

    /// Insert a 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_spectrogram_specification(
        &self,
        spec: &SpectrogramSpecification,
    ) -> Result<SpectrogramSpecification> {
        let now = Utc::now();
        let org = self.organization_id.or(spec.organization_id);
        Ok(sqlx::query_as!(
            SpectrogramSpecification,
            r#"
            INSERT INTO horizon_public.spectrogram_specification
                (id, amplitude_unit_mode, channel, frequency_spacing, name,
                 fft_sample_count, fft_sample_overlap_count,
                 organization_id, channel_role, modified_datetime)
            VALUES (COALESCE($1, gen_random_uuid()), $2, $3, $4, $5, $6, $7, $8, $9, $10)
            ON CONFLICT (id) DO UPDATE SET
                amplitude_unit_mode = EXCLUDED.amplitude_unit_mode,
                channel = EXCLUDED.channel, frequency_spacing = EXCLUDED.frequency_spacing,
                name = EXCLUDED.name, fft_sample_count = EXCLUDED.fft_sample_count, fft_sample_overlap_count = EXCLUDED.fft_sample_overlap_count,
                organization_id = EXCLUDED.organization_id,
                channel_role = EXCLUDED.channel_role,
                modified_datetime = EXCLUDED.modified_datetime
            RETURNING id, amplitude_unit_mode, created_datetime, modified_datetime, channel,
                      frequency_spacing, name, fft_sample_count, fft_sample_overlap_count,
                      organization_id, channel_role
            "#,
            spec.id,
            spec.amplitude_unit_mode,
            spec.channel,
            spec.frequency_spacing,
            spec.name,
            spec.fft_sample_count,
            spec.fft_sample_overlap_count,
            org,
            spec.channel_role,
            now,
        )
        .fetch_one(&self.pool)
        .await?)
    }
}
