const VendorRepository = require('../../repository/admin/VendorRepository.js');
const HttpException = require('../../utils/HttpException.js');
const prisma = require('../../prisma/PrismaClient.js');
const { SearchFilter } = require('../../utils/SearchFilter.js');
const timeLocal = require('../../utils/TimeLocal.js');
const { createLog, updateLog, deleteLog } = require('../../utils/LogActivity.js');
const { formatISOWithoutTimezone } = require('../../utils/FormatDate.js');

exports.getAllVendorService = async ({ page, limit, search, sortBy, orderBy }) => {
    const skip = (page - 1) * limit;

    const where = {
        ...SearchFilter(search, ['name', 'name_pt']),
        deletedAt: null
    };

    const [vendors, total] = await Promise.all([
        VendorRepository.findAll({ skip, take: limit, where, orderBy: { [sortBy]: orderBy } }),
        VendorRepository.countAll(where)
    ]);

    const formatted = vendors.map(v => ({
        ...v,
        createdAt: formatISOWithoutTimezone(v.createdAt),
        updatedAt: formatISOWithoutTimezone(v.updatedAt),
    }));

    return { vendors: formatted, total };
};

exports.showVendorService = async (id) => {
    const vendor = await VendorRepository.findById(id);
    if (!vendor) {
        throw new HttpException("Data vendor not found", 404);
    }
    
    return {
        ...vendor,
        createdAt: formatISOWithoutTimezone(vendor.createdAt),
        updatedAt: formatISOWithoutTimezone(vendor.updatedAt),
    };
};

exports.storeVendorService = async (validateData, req) => {
    const creatorId = req.user.id;

    const name_vendor = await prisma.vendor.findFirst({
        where: {
            name: validateData.name,
            deletedAt: null
        }
    });

    if (name_vendor) {
        throw new HttpException("Vendor name must be unique", 400);
    }

    const payload = {
        ...validateData,
        created_by: creatorId
    };

    const data = await VendorRepository.create(payload);
    await createLog(req, data);
};

exports.updateVendorService = async (validateData, id, req) => {
    const creatorId = req.user.id;

    const vendor = await VendorRepository.findById(id);
    if (!vendor) {
        throw new HttpException("Data vendor not found", 404);
    }

    const name_vendor = await prisma.vendor.findFirst({
        where: {
            name: validateData.name,
            deletedAt: null
        }
    });

    if (name_vendor) {
        throw new HttpException("Vendor name must be unique", 400);
    }

    const payload = {
        ...validateData,
        created_by: creatorId
    };

    const data = await VendorRepository.update(id, payload);
    await updateLog(req, data);
};

exports.deleteVendorService = async (id, req) => {
    const vendor = await VendorRepository.findById(id);

    if (!vendor) {
        throw new HttpException('Vendor not found', 404);
    }

    const data = await VendorRepository.delete(id);

    await deleteLog(req, data);
};