//! JSON shaping for order confirmation and admin order templates.

use serde_json::{json, Value};

use crate::models::_entities::{order_items, orders};
use crate::shared::money::format_price;

/// Line items of an order, shaped for templates.
pub fn items(items: &[order_items::Model]) -> Vec<Value> {
    items
        .iter()
        .map(|item| {
            json!({
                "product_name": item.product_name,
                "variant_label": item.variant_label,
                "quantity": item.quantity,
                "unit_price": format_price(item.unit_price_cents),
                "line_total": format_price(item.unit_price_cents * i64::from(item.quantity)),
            })
        })
        .collect()
}

/// Full order detail for the confirmation and admin show pages. `bank_iban` and
/// `bank_account_name` come from settings and are embedded for bank-transfer
/// payment instructions.
pub fn detail(order: &orders::Model, bank_iban: &str, bank_account_name: &str) -> Value {
    json!({
        "id": order.id,
        "order_number": order.order_number,
        "email": order.email,
        "phone": order.phone,
        "customer_name": order.customer_name,
        "account_type": order.account_type,
        "company_name": order.company_name,
        "company_id": order.company_id,
        "tax_id": order.tax_id,
        "vat_id": order.vat_id,
        "status": order.status,
        "subtotal": format_price(order.total_cents - order.shipping_cents),
        "shipping": format_price(order.shipping_cents),
        "total": format_price(order.total_cents),
        "residence_address": order.residence_address,
        "residence_city": order.residence_city,
        "residence_zip": order.residence_zip,
        "residence_country": order.residence_country,
        "address": order.address,
        "city": order.city,
        "zip": order.zip,
        "country": order.country,
        "note": order.note,
        "payment_method": order.payment_method,
        "carrier_name": order.carrier_name,
        "pickup_point_name": order.pickup_point_name,
        "tracking_number": order.tracking_number,
        "shipment_id": order.shipment_id,
        "label_url": order.label_url,
        // Numeric, sequential order id doubles as the bank variable symbol.
        "variable_symbol": order.id,
        "bank_iban": bank_iban,
        "bank_account_name": bank_account_name,
        "created_at": order.created_at.to_rfc3339(),
    })
}

/// Compact row for the admin orders list.
pub fn summary(order: &orders::Model) -> Value {
    json!({
        "id": order.id,
        "order_number": order.order_number,
        "email": order.email,
        "status": order.status,
        "total": format_price(order.total_cents),
        "created_at": order.created_at.to_rfc3339(),
    })
}
