import express from "express";
import { authenticate } from "../../middleware/auth.js";
import { withDbSession } from "../../config/db.js";

const router = express.Router();
router.use(authenticate);

function buildSearchPattern(raw) {
  const value = String(raw ?? "").trim();
  if (!value) return null;

  const escaped = value.replace(/\\/g, "\\\\");
  const hasWildcard = /[%_]/.test(escaped);

  return hasWildcard ? escaped : `%${escaped}%`;
}

router.get("/", async (req, res, next) => {
  try {
    const searchPattern = buildSearchPattern(req.query.q);

    const rows = await withDbSession(req.user, async (db) => {
      const result = await db.query(
        `
          WITH latest_reports AS (
            SELECT d.id,
                   d.document_number,
                   d.title,
                   d.description,
                   d.document_type,
                   d.version_label,
                   COALESCE(d.version_number, 1) AS version_number,
                   COALESCE(d.version_group_id, d.id) AS version_root_id,
                   COUNT(*) OVER (PARTITION BY COALESCE(d.version_group_id, d.id))::int AS version_count,
                   d.file_name,
                   d.mime_type,
                   d.size_bytes,
                   d.scan_status,
                   d.uploaded_at,
                   d.meeting_id,
                   d.case_id,
                   d.decision_id,
                   d.uploaded_by,
                   ROW_NUMBER() OVER (
                     PARTITION BY COALESCE(d.version_group_id, d.id)
                     ORDER BY COALESCE(d.version_number, 1) DESC, d.uploaded_at DESC, d.id DESC
                   ) AS version_rank
              FROM document_item d
             WHERE d.deleted_at IS NULL
               AND d.document_type = 'bericht'
          ),
          report_rows AS (
            SELECT lr.id,
                   lr.document_number,
                   lr.title,
                   lr.description,
                   lr.document_type,
                   lr.version_label,
                   lr.version_number,
                   lr.version_root_id,
                   lr.version_count,
                   lr.file_name,
                   lr.mime_type,
                   lr.size_bytes,
                   lr.scan_status,
                   lr.uploaded_at,
                   lr.meeting_id,
                   m.meeting_number,
                   lr.case_id,
                   c.case_number,
                   lr.decision_id,
                   direct_decision.decision_number AS direct_decision_number,
                   direct_decision.title AS direct_decision_title,
                   uploader.full_name AS uploaded_by_name,
                   uploader.email AS uploaded_by_email,
                   COALESCE(agenda_info.agenda_refs, '') AS agenda_refs,
                   COALESCE(decision_info.decision_refs, '') AS decision_refs
              FROM latest_reports lr
              LEFT JOIN meeting m ON m.id = lr.meeting_id
              LEFT JOIN br_case c ON c.id = lr.case_id
              LEFT JOIN decision direct_decision ON direct_decision.id = lr.decision_id
              LEFT JOIN app_user uploader ON uploader.id = lr.uploaded_by
              LEFT JOIN LATERAL (
                SELECT STRING_AGG(
                         DISTINCT TRIM(BOTH ' ' FROM CONCAT(
                           CASE
                             WHEN ai.agenda_number IS NOT NULL THEN 'TOP ' || ai.agenda_number || ' – '
                             ELSE ''
                           END,
                           COALESCE(ai.title, '')
                         )),
                         ' | '
                       ) AS agenda_refs
                  FROM meeting_agenda_item ai
                 WHERE (lr.case_id IS NOT NULL AND ai.case_id = lr.case_id)
                    OR (direct_decision.agenda_item_id IS NOT NULL AND ai.id = direct_decision.agenda_item_id)
                    OR (lr.meeting_id IS NOT NULL AND ai.meeting_id = lr.meeting_id)
              ) agenda_info ON TRUE
              LEFT JOIN LATERAL (
                SELECT STRING_AGG(
                         DISTINCT TRIM(BOTH ' ' FROM CONCAT(
                           COALESCE(d2.decision_number, 'Beschluss ' || d2.id::text),
                           CASE
                             WHEN COALESCE(d2.title, '') <> '' THEN ' – ' || d2.title
                             ELSE ''
                           END
                         )),
                         ' | '
                       ) AS decision_refs
                  FROM decision d2
                 WHERE (lr.decision_id IS NOT NULL AND d2.id = lr.decision_id)
                    OR (lr.case_id IS NOT NULL AND d2.case_id = lr.case_id)
                    OR (lr.meeting_id IS NOT NULL AND d2.meeting_id = lr.meeting_id)
              ) decision_info ON TRUE
             WHERE lr.version_rank = 1
          )
          SELECT *
            FROM report_rows
           WHERE (
             $1::text IS NULL
             OR document_number ILIKE $1 ESCAPE '\\'
             OR title ILIKE $1 ESCAPE '\\'
             OR COALESCE(description, '') ILIKE $1 ESCAPE '\\'
             OR COALESCE(file_name, '') ILIKE $1 ESCAPE '\\'
             OR COALESCE(meeting_number, '') ILIKE $1 ESCAPE '\\'
             OR COALESCE(case_number, '') ILIKE $1 ESCAPE '\\'
             OR COALESCE(agenda_refs, '') ILIKE $1 ESCAPE '\\'
             OR COALESCE(decision_refs, '') ILIKE $1 ESCAPE '\\'
             OR COALESCE(direct_decision_number, '') ILIKE $1 ESCAPE '\\'
             OR COALESCE(direct_decision_title, '') ILIKE $1 ESCAPE '\\'
           )
           ORDER BY uploaded_at DESC, id DESC
        `,
        [searchPattern]
      );

      return result.rows;
    });

    res.json(rows);
  } catch (err) {
    next(err);
  }
});

export default router;
