use scythe_backend::manifest::BackendManifest;
use scythe_backend::naming::{
    enum_type_name, fn_name, row_struct_name, to_camel_case, to_pascal_case,
};
use scythe_backend::types::resolve_type;
use std::collections::HashMap;
use std::fmt::Write;

use scythe_core::analyzer::{AnalyzedQuery, CompositeInfo, EnumInfo};
use scythe_core::errors::{ErrorCode, ScytheError};
use scythe_core::parser::QueryCommand;

use crate::backend_trait::{CodegenBackend, ResolvedColumn, ResolvedParam};
use crate::backends::typescript_common::TsRowType;
use crate::singularize;

const DEFAULT_MANIFEST_TOML: &str = include_str!("../../manifests/typescript-oracledb.toml");

pub struct TypescriptOracledbBackend {
    manifest: BackendManifest,
    row_type: TsRowType,
}

impl TypescriptOracledbBackend {
    pub fn new(engine: &str) -> Result<Self, ScytheError> {
        match engine {
            "oracle" => {}
            _ => {
                return Err(ScytheError::new(
                    ErrorCode::InternalError,
                    format!(
                        "typescript-oracledb only supports Oracle, got engine '{}'",
                        engine
                    ),
                ));
            }
        }
        let manifest = super::load_or_default_manifest(
            "backends/typescript-oracledb/manifest.toml",
            DEFAULT_MANIFEST_TOML,
        )?;
        Ok(Self {
            manifest,
            row_type: TsRowType::default(),
        })
    }
}

/// Rewrite $1, $2, ... positional params to :1, :2, ... for Oracle.
impl CodegenBackend for TypescriptOracledbBackend {
    fn name(&self) -> &str {
        "typescript-oracledb"
    }

    fn manifest(&self) -> &scythe_backend::manifest::BackendManifest {
        &self.manifest
    }

    fn supported_engines(&self) -> &[&str] {
        &["oracle"]
    }

    fn apply_options(&mut self, options: &HashMap<String, String>) -> Result<(), ScytheError> {
        if let Some(rt) = options.get("row_type") {
            self.row_type = TsRowType::from_option(rt)?;
        }
        Ok(())
    }

    fn file_header(&self) -> String {
        "// Auto-generated by scythe. Do not edit.\nimport oracledb from 'oracledb';\n".to_string()
    }

    fn generate_row_struct(
        &self,
        query_name: &str,
        columns: &[ResolvedColumn],
    ) -> Result<String, ScytheError> {
        let struct_name = row_struct_name(query_name, &self.manifest.naming);
        let mut out = String::new();
        let _ = writeln!(out, "export interface {} {{", struct_name);
        for col in columns {
            let _ = writeln!(out, "\t{}: {};", col.field_name, col.full_type);
        }
        let _ = write!(out, "}}");
        Ok(out)
    }

    fn generate_model_struct(
        &self,
        table_name: &str,
        columns: &[ResolvedColumn],
    ) -> Result<String, ScytheError> {
        let singular = singularize(table_name);
        let name = to_pascal_case(&singular);
        self.generate_row_struct(&name, columns)
    }

    fn generate_query_fn(
        &self,
        analyzed: &AnalyzedQuery,
        struct_name: &str,
        columns: &[ResolvedColumn],
        params: &[ResolvedParam],
    ) -> Result<String, ScytheError> {
        let func_name = fn_name(&analyzed.name, &self.manifest.naming);
        let sql = super::rewrite_pg_placeholders(
            &super::clean_sql_oneline_with_optional(
                &analyzed.sql,
                &analyzed.optional_params,
                &analyzed.params,
            ),
            |n| format!(":{n}"),
        );

        let param_list = params
            .iter()
            .map(|p| format!("{}: {}", p.field_name, p.full_type))
            .collect::<Vec<_>>()
            .join(", ");
        let sep = if param_list.is_empty() { "" } else { ", " };

        let bind_array = if params.is_empty() {
            "[]".to_string()
        } else {
            format!(
                "[{}]",
                params
                    .iter()
                    .map(|p| p.field_name.clone())
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        };

        // Check if this is a DML with RETURNING (INSERT/UPDATE/DELETE RETURNING)
        let has_returning = sql.to_uppercase().contains("RETURNING");

        let mut out = String::new();

        match &analyzed.command {
            QueryCommand::One | QueryCommand::Opt => {
                let _ = writeln!(
                    out,
                    "export async function {}(conn: oracledb.Connection{}{}): Promise<{} | null> {{",
                    func_name, sep, param_list, struct_name
                );

                if has_returning {
                    // Oracle RETURNING requires output bind variables via INTO clause.
                    // node-oracledb uses { dir: oracledb.BIND_OUT, type: oracledb.NUMBER/STRING/DATE }
                    let out_bind_entries: Vec<String> = columns
                        .iter()
                        .map(|col| {
                            let nt = col.neutral_type.as_str();
                            let oratype = match nt {
                                "int32" | "int64" | "float32" | "float64" | "decimal" => {
                                    "oracledb.NUMBER"
                                }
                                "date" | "datetime" | "datetime_tz" | "time" | "time_tz" => {
                                    "oracledb.DATE"
                                }
                                _ => "oracledb.STRING",
                            };
                            format!("{{ dir: oracledb.BIND_OUT, type: {} }}", oratype)
                        })
                        .collect();
                    let into_clause = columns
                        .iter()
                        .enumerate()
                        .map(|(i, _)| format!(":{}", params.len() + i + 1))
                        .collect::<Vec<_>>()
                        .join(", ");
                    let full_sql = format!("{} INTO {}", sql, into_clause);
                    let all_binds = if params.is_empty() {
                        format!("[{}]", out_bind_entries.join(", "))
                    } else {
                        let input_names: Vec<String> =
                            params.iter().map(|p| p.field_name.clone()).collect();
                        format!(
                            "[{}, {}]",
                            input_names.join(", "),
                            out_bind_entries.join(", ")
                        )
                    };
                    let _ = writeln!(
                        out,
                        "\tconst result = await conn.execute(\"{}\", {});",
                        full_sql, all_binds
                    );
                    let _ = writeln!(out, "\tif (!result.outBinds) {{");
                    let _ = writeln!(out, "\t\treturn null;");
                    let _ = writeln!(out, "\t}}");
                    let _ = writeln!(out, "\tconst outBinds = result.outBinds as unknown[][];");
                    let _ = writeln!(out, "\treturn {{");
                    for (i, col) in columns.iter().enumerate() {
                        let _ = writeln!(
                            out,
                            "\t\t{}: outBinds[{}][0] as {},",
                            col.field_name, i, col.lang_type
                        );
                    }
                    let _ = writeln!(out, "\t}};");
                    let _ = write!(out, "}}");
                } else {
                    let _ = writeln!(
                        out,
                        "\tconst result = await conn.execute(\"{}\", {}, {{ outFormat: oracledb.OUT_FORMAT_OBJECT }});",
                        sql, bind_array
                    );
                    let _ = writeln!(out, "\tif (!result.rows || result.rows.length === 0) {{");
                    let _ = writeln!(out, "\t\treturn null;");
                    let _ = writeln!(out, "\t}}");
                    let _ = writeln!(
                        out,
                        "\tconst row = result.rows[0] as Record<string, unknown>;"
                    );
                    let _ = writeln!(out, "\treturn {{");
                    for col in columns {
                        // Oracle returns column names as uppercase by default for unquoted identifiers.
                        let _ = writeln!(
                            out,
                            "\t\t{}: row[\"{}\"] as {},",
                            col.field_name,
                            col.name.to_uppercase(),
                            col.lang_type
                        );
                    }
                    let _ = writeln!(out, "\t}};");
                    let _ = write!(out, "}}");
                }
            }
            QueryCommand::Many => {
                let _ = writeln!(
                    out,
                    "export async function {}(conn: oracledb.Connection{}{}): Promise<{}[]> {{",
                    func_name, sep, param_list, struct_name
                );
                let _ = writeln!(
                    out,
                    "\tconst result = await conn.execute(\"{}\", {}, {{ outFormat: oracledb.OUT_FORMAT_OBJECT }});",
                    sql, bind_array
                );
                let _ = writeln!(out, "\tif (!result.rows) {{");
                let _ = writeln!(out, "\t\treturn [];");
                let _ = writeln!(out, "\t}}");
                let _ = writeln!(
                    out,
                    "\treturn result.rows.map((row: Record<string, unknown>) => ({{",
                );
                for col in columns {
                    // Oracle returns column names as uppercase by default for unquoted identifiers.
                    let _ = writeln!(
                        out,
                        "\t\t{}: row[\"{}\"] as {},",
                        col.field_name,
                        col.name.to_uppercase(),
                        col.lang_type
                    );
                }
                let _ = writeln!(out, "\t}}));");
                let _ = write!(out, "}}");
            }
            QueryCommand::Exec => {
                let _ = writeln!(
                    out,
                    "export async function {}(conn: oracledb.Connection{}{}): Promise<void> {{",
                    func_name, sep, param_list
                );
                let _ = writeln!(out, "\tawait conn.execute(\"{}\", {});", sql, bind_array);
                let _ = write!(out, "}}");
            }
            QueryCommand::ExecResult | QueryCommand::ExecRows => {
                let _ = writeln!(
                    out,
                    "export async function {}(conn: oracledb.Connection{}{}): Promise<number> {{",
                    func_name, sep, param_list
                );
                let _ = writeln!(
                    out,
                    "\tconst result = await conn.execute(\"{}\", {});",
                    sql, bind_array
                );
                let _ = writeln!(out, "\treturn result.rowsAffected ?? 0;");
                let _ = write!(out, "}}");
            }
            QueryCommand::Batch => {
                let batch_fn_name = format!("{}Batch", func_name);
                let items_type = if params.len() > 1 {
                    let tuple_types: Vec<String> =
                        params.iter().map(|p| p.full_type.clone()).collect();
                    format!("[{}]", tuple_types.join(", "))
                } else if params.len() == 1 {
                    params[0].full_type.clone()
                } else {
                    "number".to_string()
                };
                let _ = writeln!(
                    out,
                    "export async function {}(conn: oracledb.Connection, items: {}[]): Promise<void> {{",
                    batch_fn_name, items_type
                );
                if params.is_empty() {
                    let _ = writeln!(out, "\tfor (let i = 0; i < items.length; i++) {{");
                    let _ = writeln!(out, "\t\tawait conn.execute(\"{}\");", sql);
                    let _ = writeln!(out, "\t}}");
                } else {
                    let _ = writeln!(
                        out,
                        "\tawait conn.executeMany(\"{}\", items.map(item => Array.isArray(item) ? item : [item]));",
                        sql
                    );
                }
                let _ = write!(out, "}}");
            }
            QueryCommand::Grouped => unreachable!("Grouped is rewritten to Many before codegen"),
        }

        Ok(out)
    }

    fn generate_enum_def(&self, enum_info: &EnumInfo) -> Result<String, ScytheError> {
        let type_name = enum_type_name(&enum_info.sql_name, &self.manifest.naming);
        let mut out = String::new();
        let values: Vec<String> = enum_info
            .values
            .iter()
            .map(|v| format!("\"{}\"", v))
            .collect();
        let _ = writeln!(out, "export type {} = {};", type_name, values.join(" | "));
        Ok(out)
    }

    fn generate_composite_def(&self, composite: &CompositeInfo) -> Result<String, ScytheError> {
        let name = to_pascal_case(&composite.sql_name);
        let mut out = String::new();
        let _ = writeln!(out, "export interface {} {{", name);
        for field in &composite.fields {
            let ts_type = resolve_type(&field.neutral_type, &self.manifest, false)
                .map(|t| t.into_owned())
                .map_err(|e| {
                    ScytheError::new(
                        ErrorCode::InternalError,
                        format!("composite field type error: {}", e),
                    )
                })?;
            let _ = writeln!(out, "\t{}: {};", to_camel_case(&field.name), ts_type);
        }
        let _ = write!(out, "}}");
        Ok(out)
    }
}
