import {
  createApplicationSchema,
  updateApplicationSchema,
  normalizeApplicationPayload,
} from "../models/application.schema.js";
import {
  listApplications,
  getApplicationById,
  createApplication,
  updateApplication,
  deleteApplication,
} from "../services/applications.service.js";
import { successResponse, errorResponse } from "../utils/response.js";
import { HTTP_STATUS } from "../constants/index.js";
import logger from "../utils/logger.js";

export const list = async (req, res, next) => {
  try {
    const filters = {
      status: req.query.status,
      jobId: req.query.jobId,
    };
    const items = await listApplications(filters);
    return successResponse(res, items, HTTP_STATUS.OK);
  } catch (err) {
    logger.error("Error listing applications:", err);
    next(err);
  }
};

export const getById = async (req, res, next) => {
  try {
    const { id } = req.params;
    if (!id) {
      return errorResponse(res, "Application ID is required", HTTP_STATUS.BAD_REQUEST);
    }
    const item = await getApplicationById(id);
    if (!item) {
      return errorResponse(res, "Application not found", HTTP_STATUS.NOT_FOUND);
    }
    return successResponse(res, item, HTTP_STATUS.OK);
  } catch (err) {
    logger.error("Error getting application by ID:", err);
    next(err);
  }
};

export const create = async (req, res, next) => {
  try {
    const normalized = normalizeApplicationPayload(req.body);
    const parsed = createApplicationSchema.safeParse(normalized);
    if (!parsed.success) {
      return errorResponse(
        res,
        "Validation failed",
        HTTP_STATUS.BAD_REQUEST,
        parsed.error.flatten()
      );
    }
    const created = await createApplication(parsed.data);
    logger.info(`Application created with ID: ${created._id}`);
    return successResponse(res, created, HTTP_STATUS.CREATED);
  } catch (err) {
    logger.error("Error creating application:", err);
    next(err);
  }
};

export const update = async (req, res, next) => {
  try {
    const { id } = req.params;
    if (!id) {
      return errorResponse(res, "Application ID is required", HTTP_STATUS.BAD_REQUEST);
    }
    const normalized = normalizeApplicationPayload(req.body);
    const parsed = updateApplicationSchema.safeParse(normalized);
    if (!parsed.success) {
      return errorResponse(
        res,
        "Validation failed",
        HTTP_STATUS.BAD_REQUEST,
        parsed.error.flatten()
      );
    }
    const updated = await updateApplication(id, parsed.data);
    if (!updated) {
      return errorResponse(res, "Application not found", HTTP_STATUS.NOT_FOUND);
    }
    logger.info(`Application updated with ID: ${id}`);
    return successResponse(res, updated, HTTP_STATUS.OK);
  } catch (err) {
    logger.error("Error updating application:", err);
    next(err);
  }
};

export const remove = async (req, res, next) => {
  try {
    const { id } = req.params;
    if (!id) {
      return errorResponse(res, "Application ID is required", HTTP_STATUS.BAD_REQUEST);
    }
    const ok = await deleteApplication(id);
    if (!ok) {
      return errorResponse(res, "Application not found", HTTP_STATUS.NOT_FOUND);
    }
    logger.info(`Application deleted with ID: ${id}`);
    return res.status(HTTP_STATUS.NO_CONTENT).send();
  } catch (err) {
    logger.error("Error deleting application:", err);
    next(err);
  }
};

