const db = require('../models');
const { sendSuccess, sendError } = require('../utils/response');
const asyncHandler = require('../middlewares/asyncHandler');
const { Op } = require('sequelize');

// Get all machine history cards
exports.getAll = asyncHandler(async (req, res) => {
  const {
    page = 1,
    limit = 25,
    search = '',
    company_id,
    plant_id,
    fiscal_year_id,
    machine_id,
    status,
    date_from,
    date_to
  } = req.query;

  const offset = (page - 1) * limit;
  const where = {};

  if (company_id) where.company_id = company_id;
  if (plant_id) where.plant_id = plant_id;
  if (fiscal_year_id) where.fiscal_year_id = fiscal_year_id;
  if (machine_id) where.machine_id = machine_id;
  if (status) where.status = status;

  if (date_from && date_to) {
    where.date = { [Op.between]: [date_from, date_to] };
  } else if (date_from) {
    where.date = { [Op.gte]: date_from };
  } else if (date_to) {
    where.date = { [Op.lte]: date_to };
  }

  if (search) {
    where[Op.or] = [
      { machine_number: { [Op.like]: `%${search}%` } },
      { machine_description: { [Op.like]: `%${search}%` } },
      { problem_details: { [Op.like]: `%${search}%` } },
      { action_taken: { [Op.like]: `%${search}%` } }
    ];
  }

  const { count, rows } = await db.MachineHistoryCard.findAndCountAll({
    where,
    include: [
      {
        model: db.Company,
        as: 'company',
        attributes: ['id', 'code', 'name']
      },
      {
        model: db.Plant,
        as: 'plant',
        attributes: ['id', 'code', 'name']
      },
      {
        model: db.FiscalYear,
        as: 'fiscalYear',
        attributes: ['id', 'fiscal_year', 'start_date', 'end_date']
      },
      {
        model: db.Machine,
        as: 'machine',
        attributes: ['id', 'machine_code', 'machine_description', 'history_card_no']
      },
      {
        model: db.User,
        as: 'creator',
        attributes: ['id', 'username', 'email']
      }
    ],
    limit: parseInt(limit),
    offset: parseInt(offset),
    order: [['date', 'DESC'], ['id', 'DESC']],
    distinct: true
  });

  return sendSuccess(
    res,
    'Machine History Cards fetched successfully',
    {
      items: rows,
      pagination: {
        total: count,
        page: parseInt(page),
        limit: parseInt(limit),
        pages: Math.ceil(count / limit)
      }
    }
  );
});

// Get by ID
exports.getById = asyncHandler(async (req, res) => {
  const { id } = req.params;

  const historyCard = await db.MachineHistoryCard.findByPk(id, {
    include: [
      {
        model: db.Company,
        as: 'company',
        attributes: ['id', 'code', 'name']
      },
      {
        model: db.Plant,
        as: 'plant',
        attributes: ['id', 'code', 'name']
      },
      {
        model: db.FiscalYear,
        as: 'fiscalYear',
        attributes: ['id', 'fiscal_year', 'start_date', 'end_date']
      },
      {
        model: db.Machine,
        as: 'machine',
        attributes: ['id', 'machine_code', 'machine_description', 'history_card_no']
      },
      {
        model: db.User,
        as: 'creator',
        attributes: ['id', 'username', 'email']
      },
      {
        model: db.User,
        as: 'updater',
        attributes: ['id', 'username', 'email']
      }
    ]
  });

  if (!historyCard) {
    return sendError(res, 'Machine History Card not found', 404);
  }

  return sendSuccess(res, 'Machine History Card fetched successfully', historyCard);
});

// Create
exports.create = asyncHandler(async (req, res) => {
  const userId = req.user?.id;

  const historyCard = await db.MachineHistoryCard.create({
    ...req.body,
    created_by: userId,
    updated_by: userId
  });

  const createdCard = await db.MachineHistoryCard.findByPk(historyCard.id, {
    include: [
      {
        model: db.Company,
        as: 'company',
        attributes: ['id', 'code', 'name']
      },
      {
        model: db.Plant,
        as: 'plant',
        attributes: ['id', 'code', 'name']
      },
      {
        model: db.FiscalYear,
        as: 'fiscalYear',
        attributes: ['id', 'fiscal_year']
      },
      {
        model: db.Machine,
        as: 'machine',
        attributes: ['id', 'machine_code', 'machine_description', 'history_card_no']
      }
    ]
  });

  return sendSuccess(res, 'Machine History Card created successfully', createdCard, null, 201);
});

// Update
exports.update = asyncHandler(async (req, res) => {
  const { id } = req.params;
  const userId = req.user?.id;

  const historyCard = await db.MachineHistoryCard.findByPk(id);

  if (!historyCard) {
    return sendError(res, 'Machine History Card not found', 404);
  }

  await historyCard.update({
    ...req.body,
    updated_by: userId
  });

  const updatedCard = await db.MachineHistoryCard.findByPk(id, {
    include: [
      {
        model: db.Company,
        as: 'company',
        attributes: ['id', 'code', 'name']
      },
      {
        model: db.Plant,
        as: 'plant',
        attributes: ['id', 'code', 'name']
      },
      {
        model: db.FiscalYear,
        as: 'fiscalYear',
        attributes: ['id', 'fiscal_year']
      },
      {
        model: db.Machine,
        as: 'machine',
        attributes: ['id', 'machine_code', 'machine_description', 'history_card_no']
      }
    ]
  });

  return sendSuccess(res, 'Machine History Card updated successfully', updatedCard);
});

// Delete
exports.delete = asyncHandler(async (req, res) => {
  const { id } = req.params;

  const historyCard = await db.MachineHistoryCard.findByPk(id);

  if (!historyCard) {
    return sendError(res, 'Machine History Card not found', 404);
  }

  await historyCard.destroy();

  return sendSuccess(res, 'Machine History Card deleted successfully', null);
});

// Get machine history by machine ID
exports.getByMachineId = asyncHandler(async (req, res) => {
  const { machineId } = req.params;
  const { page = 1, limit = 25 } = req.query;

  const offset = (page - 1) * limit;

  const { count, rows } = await db.MachineHistoryCard.findAndCountAll({
    where: { machine_id: machineId },
    include: [
      {
        model: db.User,
        as: 'creator',
        attributes: ['id', 'username', 'email']
      }
    ],
    limit: parseInt(limit),
    offset: parseInt(offset),
    order: [['date', 'DESC']],
    distinct: true
  });

  return sendSuccess(
    res,
    'Machine History Cards fetched successfully',
    {
      items: rows,
      pagination: {
        total: count,
        page: parseInt(page),
        limit: parseInt(limit),
        pages: Math.ceil(count / limit)
      }
    }
  );
});
