const path = require("path");
const db = require("../../db");
const fs = require("fs");

exports.getAllCompanies = async (req, res) => {
  try {
    const companies = await db.Company.findAll({
      attributes: ["id", "company", "image", "status"],
    });
    res.json({ success: true, data: companies });
  } catch (err) {
    console.error(err);
    res
      .status(500)
      .json({ success: false, message: "Failed to fetch companies" });
  }
};

exports.createCompany = async (req, res) => {
  try {
    const { company, status } = req.body;
    const imageName = req.file ? req.file.filename : null;

    const newCompany = await db.Company.create({
      company,
      image: imageName,
      status: status || 1,
    });

    res.status(201).json({
      success: true,
      data: {
        id: newCompany.id,
        company: newCompany.company,
        image: newCompany.image,
        status: newCompany.status,
      },
    });
  } catch (err) {
    console.error(err);
    res
      .status(500)
      .json({ success: false, message: "Failed to create company" });
  }
};

exports.updateCompany = async (req, res) => {
  try {
    const company = await db.Company.findByPk(req.params.id);
    if (!company) {
      return res
        .status(404)
        .json({ success: false, message: "Company not found" });
    }

    const updateData = {
      company: req.body.company || company.company,
      status: req.body.status || company.status,
    };

    if (req.file) {
      updateData.image = req.file.filename;
    }

    await company.update(updateData);

    res.json({
      success: true,
      data: {
        id: company.id,
        company: company.company,
        image: company.image,
        status: company.status,
      },
    });
  } catch (err) {
    console.error(err);
    res
      .status(500)
      .json({ success: false, message: "Failed to update company" });
  }
};

exports.deleteCompany = async (req, res) => {
  try {
    const deleted = await db.Company.destroy({ where: { id: req.params.id } });

    if (!deleted) {
      return res
        .status(404)
        .json({ success: false, message: "Company not found" });
    }

    res.json({ success: true, message: "Company deleted successfully" });
  } catch (err) {
    console.error(err);
    res
      .status(500)
      .json({ success: false, message: "Failed to delete company" });
  }
};
