
const express = require("express");
const router = express.Router();
// const controller = require("../../controllers/hrandpayrollsController/hrLetterController");
// const authenticate = require("../../middlewares/authenticate");
const controller = require("../../controllers/hrandpayrollsController/hrLettersController");
const authenticate = require("../../middlewares/authenticate");


/**
 * @swagger
 * tags:
 *   name: HR Letters
 *   description: HR letters management, document types, generation, and audit trail APIs
 */

/* ── Document types ────────────────────────── */
// GET  /api/hr-letters/documents → list all 6 doc types
router.get("/documents", authenticate, (req, res) => {
  /*
    #swagger.tags = ['HR Letters']
    #swagger.summary = 'Get all HR document types (6 master document types)'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['is_active'] = { in: 'query', type: 'boolean', description: 'Filter by active status' }
    #swagger.responses[200] = {
      description: 'Document types retrieved successfully',
      schema: {
        type: "object",
        properties: {
          success: { type: "boolean" },
          data: {
            type: "array",
            items: {
              type: "object",
              properties: {
                id: { type: "integer" },
                doc_code: { type: "string" },
                doc_name: { type: "string" },
                description: { type: "string" },
                is_active: { type: "boolean" }
              }
            }
          }
        }
      }
    }
    #swagger.responses[401] = {
      description: 'Unauthorized - Invalid or missing token'
    }
  */
  controller.getHrDocuments(req, res);
});

/* ── Stats ─────────────────────────────────── */
// GET  /api/hr-letters/stats → letter generation stats
router.get("/stats", authenticate, (req, res) => {
  /*
    #swagger.tags = ['HR Letters']
    #swagger.summary = 'Get letter generation statistics'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['start_date'] = { in: 'query', type: 'string', format: 'date', description: 'Start date for stats' }
    #swagger.parameters['end_date'] = { in: 'query', type: 'string', format: 'date', description: 'End date for stats' }
    #swagger.parameters['doc_code'] = { in: 'query', type: 'string', description: 'Filter by document code' }
    #swagger.responses[200] = {
      description: 'Statistics retrieved successfully',
      schema: {
        type: "object",
        properties: {
          success: { type: "boolean" },
          data: {
            type: "object",
            properties: {
              total_letters: { type: "integer" },
              by_document_type: { type: "object" },
              by_month: { type: "object" },
              recent_generations: { type: "integer" }
            }
          }
        }
      }
    }
  */
  controller.getLetterStats(req, res);
});

/* ── Generated letters (history) ───────────── */
// GET  /api/hr-letters/generated → all generated letters (audit trail)
router.get("/generated", authenticate, (req, res) => {
  /*
    #swagger.tags = ['HR Letters']
    #swagger.summary = 'Get all generated letters audit trail'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['page'] = { in: 'query', type: 'integer', description: 'Page number', default: 1 }
    #swagger.parameters['limit'] = { in: 'query', type: 'integer', description: 'Items per page', default: 10 }
    #swagger.parameters['employee_id'] = { in: 'query', type: 'integer', description: 'Filter by employee ID' }
    #swagger.parameters['doc_code'] = { in: 'query', type: 'string', description: 'Filter by document code' }
    #swagger.parameters['start_date'] = { in: 'query', type: 'string', format: 'date', description: 'Start date filter' }
    #swagger.parameters['end_date'] = { in: 'query', type: 'string', format: 'date', description: 'End date filter' }
    #swagger.parameters['search'] = { in: 'query', type: 'string', description: 'Search in letter content' }
    #swagger.responses[200] = {
      description: 'Generated letters retrieved successfully',
      schema: {
        type: "object",
        properties: {
          success: { type: "boolean" },
          data: {
            type: "array",
            items: {
              type: "object",
              properties: {
                id: { type: "integer" },
                employee_name: { type: "string" },
                doc_name: { type: "string" },
                generated_at: { type: "string", format: "date-time" },
                generated_by: { type: "string" }
              }
            }
          },
          pagination: {
            type: "object",
            properties: {
              page: { type: "integer" },
              limit: { type: "integer" },
              total: { type: "integer" },
              totalPages: { type: "integer" }
            }
          }
        }
      }
    }
  */
  controller.getGeneratedLetters(req, res);
});

// GET  /api/hr-letters/generated/:id → single generated letter raw row
router.get("/generated/:id", authenticate, (req, res) => {
  /*
    #swagger.tags = ['HR Letters']
    #swagger.summary = 'Get single generated letter by ID (raw database row)'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['id'] = {
      in: 'path',
      required: true,
      type: 'integer',
      description: 'Generated letter ID'
    }
    #swagger.responses[200] = {
      description: 'Generated letter retrieved successfully',
      schema: {
        type: "object",
        properties: {
          success: { type: "boolean" },
          data: {
            type: "object",
            properties: {
              id: { type: "integer" },
              employee_id: { type: "integer" },
              doc_id: { type: "integer" },
              letter_content: { type: "string" },
              generated_at: { type: "string", format: "date-time" },
              generated_by: { type: "string" },
              variables_used: { type: "object" }
            }
          }
        }
      }
    }
    #swagger.responses[404] = {
      description: 'Generated letter not found'
    }
  */
  controller.getGeneratedLetterById(req, res);
});

// GET  /api/hr-letters/generated/:id/data → letter data shaped for JSX components
router.get("/generated/:id/data", authenticate, (req, res) => {
  /*
    #swagger.tags = ['HR Letters']
    #swagger.summary = 'Get generated letter data shaped for JSX components (pre-filled form data)'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['id'] = {
      in: 'path',
      required: true,
      type: 'integer',
      description: 'Generated letter ID'
    }
    #swagger.responses[200] = {
      description: 'Letter data retrieved successfully for JSX components',
      schema: {
        type: "object",
        properties: {
          success: { type: "boolean" },
          data: {
            type: "object",
            properties: {
              letter_id: { type: "integer" },
              employee_details: { type: "object" },
              document_details: { type: "object" },
              variables: { type: "object" },
              formatted_content: { type: "string" }
            }
          }
        }
      }
    }
    #swagger.responses[404] = {
      description: 'Letter data not found'
    }
  */
  controller.getLetterData(req, res);
});

// DELETE /api/hr-letters/generated/:id → soft-delete a generated letter
router.delete("/generated/:id", authenticate, (req, res) => {
  /*
    #swagger.tags = ['HR Letters']
    #swagger.summary = 'Soft delete a generated letter from audit log'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['id'] = {
      in: 'path',
      required: true,
      type: 'integer',
      description: 'Generated letter ID'
    }
    #swagger.responses[200] = {
      description: 'Letter deleted successfully',
      schema: {
        type: "object",
        properties: {
          success: { type: "boolean" },
          message: { type: "string" }
        }
      }
    }
    #swagger.responses[404] = {
      description: 'Generated letter not found'
    }
  */
  controller.deleteGeneratedLetter(req, res);
});

/* ── Generate a new letter ─────────────────── */
// POST /api/hr-letters/generate
// Body: { doc_code, employee_db_id, issue_date?, relieving_date?,
//         start_date?, warning_issue?, performance?,
//         place?, sign_authority?, hr_name?, company? }
router.post("/generate", authenticate, (req, res) => {
  /*
    #swagger.tags = ['HR Letters']
    #swagger.summary = 'Generate a new HR letter with dynamic variables'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.requestBody = {
      required: true,
      content: {
        "application/json": {
          schema: {
            type: "object",
            properties: {
              doc_code: { 
                type: "string", 
                description: "Document code (e.g., OFFER_LETTER, APPOINTMENT_LETTER, etc.)",
                enum: ["OFFER_LETTER", "APPOINTMENT_LETTER", "EXPERIENCE_LETTER", "WARNING_LETTER", "RELIEVING_LETTER", "TERMINATION_LETTER"]
              },
              employee_db_id: { type: "integer", description: "Employee database ID" },
              issue_date: { type: "string", format: "date", description: "Issue date of the letter" },
              relieving_date: { type: "string", format: "date", description: "Relieving date (for relieving letters)" },
              start_date: { type: "string", format: "date", description: "Start date (for appointment letters)" },
              warning_issue: { type: "string", description: "Warning issue description (for warning letters)" },
              performance: { type: "string", description: "Performance remarks (for experience letters)" },
              place: { type: "string", description: "Place of issue" },
              sign_authority: { type: "string", description: "Signing authority name" },
              hr_name: { type: "string", description: "HR representative name" },
              company: { type: "string", description: "Company name" },
              additional_variables: { 
                type: "object", 
                description: "Any additional custom variables for the letter template",
                additionalProperties: { type: "string" }
              }
            },
            required: ["doc_code", "employee_db_id"]
          }
        }
      }
    }
    #swagger.responses[201] = {
      description: 'Letter generated successfully',
      schema: {
        type: "object",
        properties: {
          success: { type: "boolean" },
          message: { type: "string" },
          data: {
            type: "object",
            properties: {
              letter_id: { type: "integer" },
              download_url: { type: "string" },
              preview_content: { type: "string" },
              generated_at: { type: "string", format: "date-time" }
            }
          }
        }
      }
    }
    #swagger.responses[400] = {
      description: 'Bad request - Invalid data or missing required fields'
    }
    #swagger.responses[404] = {
      description: 'Employee or document type not found'
    }
  */
  controller.generateLetter(req, res);
});

// Add this route after your other /generated/:id routes
// GET /api/hr-letters/generated/:id/pdf → download letter as PDF
router.get("/generated/:id/pdf", authenticate, (req, res) => {
  /*
    #swagger.tags = ['HR Letters']
    #swagger.summary = 'Download generated letter as PDF'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['id'] = {
      in: 'path',
      description: 'Generated letter ID',
      required: true,
      type: 'integer'
    }
  } */
  controller.downloadLetterPDF(req, res);
});

// Optional: Preview HTML (useful for testing)
router.get("/generated/:id/preview", authenticate, (req, res) => {
  /*
    #swagger.tags = ['HR Letters']
    #swagger.summary = 'Preview generated letter as HTML (for testing)'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['id'] = {
      in: 'path',
      description: 'Generated letter ID',
      required: true,
      type: 'integer'
    }
  } */
  controller.previewLetterHTML(req, res);
});

// In your routes file
// router.get("/letters-history", authenticate, (req, res) => {
//   // This route renders the page
//    controller.getGeneratedLetters (req, res);
// });

module.exports = router;