CREATE OR REPLACE VIEW mv_reports_ucepsa_demo.machine_stops_grafana AS
SELECT
    s.id,
    s.machine_id,

    s.started_at,
    s.ended_at,
    COALESCE(s.ended_at, now()) AS effective_ended_at,

    s.status,
    s.classification_status,

    s.start_event_name,
    s.end_event_name,

    COALESCE(
        s.duration_s,
        EXTRACT(EPOCH FROM (COALESCE(s.ended_at, now()) - s.started_at))
    ) AS duration_s_current,

    ROUND(
        (
            COALESCE(
                s.duration_s,
                EXTRACT(EPOCH FROM (COALESCE(s.ended_at, now()) - s.started_at))
            ) / 60.0
        )::numeric,
        2
    ) AS duration_min,

    COALESCE(s.cost_eur, 0)::numeric AS cost_eur,

    COALESCE(
        to_jsonb(s) ->> 'cause_code',
        to_jsonb(s) ->> 'stop_cause_code',
        to_jsonb(s) ->> 'reason_code',
        to_jsonb(c) ->> 'code',
        to_jsonb(c) ->> 'cause_code',
        CASE
            WHEN s.classification_status = 'PENDING' THEN 'PENDIENTE'
            ELSE 'SIN_CAUSA'
        END
    ) AS cause_code,

    COALESCE(
        to_jsonb(s) ->> 'cause_name',
        to_jsonb(s) ->> 'stop_cause_name',
        to_jsonb(s) ->> 'reason_name',
        to_jsonb(c) ->> 'name',
        to_jsonb(c) ->> 'description',
        to_jsonb(c) ->> 'label',
        CASE
            WHEN s.classification_status = 'PENDING' THEN 'Pendiente de clasificar'
            ELSE 'Sin causa registrada'
        END
    ) AS cause_name,

    to_jsonb(s) ->> 'operator_note' AS operator_note,
    to_jsonb(s) ->> 'classified_by' AS classified_by,
    to_jsonb(s) ->> 'classified_at' AS classified_at,
    to_jsonb(s) ->> 'order_ref' AS order_ref,
    to_jsonb(s) ->> 'production_order' AS production_order,

    CASE WHEN s.status = 'OPEN' THEN true ELSE false END AS is_open,

    CASE
        WHEN s.classification_status = 'PENDING' THEN true
        ELSE false
    END AS is_pending_classification,

    CASE
        WHEN s.status = 'OPEN' THEN 'ABIERTO'
        WHEN s.classification_status = 'PENDING' THEN 'CERRADO SIN CLASIFICAR'
        WHEN s.classification_status = 'CLASSIFIED' THEN 'CLASIFICADO'
        ELSE COALESCE(s.status, 'SIN_ESTADO')
    END AS stop_status_label,

    CASE
        WHEN s.status = 'OPEN' THEN 3
        WHEN s.classification_status = 'PENDING' THEN 2
        WHEN s.classification_status = 'CLASSIFIED' THEN 1
        ELSE 0
    END AS stop_priority_score

FROM mv_hot.edge_oee_machine_stops s
LEFT JOIN mv_hot.edge_oee_stop_causes c
    ON (to_jsonb(c) ->> 'id') = COALESCE(
        to_jsonb(s) ->> 'cause_id',
        to_jsonb(s) ->> 'stop_cause_id',
        to_jsonb(s) ->> 'reason_id'
    );

GRANT SELECT ON mv_reports_ucepsa_demo.machine_stops_grafana TO grafana_ucepsa_ro;
