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

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

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

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

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

    return { provinces: formatted, total };
};

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

exports.storeProvinceService = async (validateData, req) => {
    const province = await ProvinceRepository.create(validateData);
    await createLog(req, province);
};

exports.updateProvinceService = async (validateData, id, req) => {
    const province = await ProvinceRepository.findById(id);
    if (!province) {
        throw new HttpException("Data province not found", 404);
    }

    const data = await ProvinceRepository.update(id, validateData);
    await updateLog(req, data);
};

exports.deleteProvinceService = async (id, req) => {
    const province = await ProvinceRepository.findById(id);
    if (!province) {
        throw new HttpException("Data province not found", 404);
    }

    const data = await ProvinceRepository.update(id, {
        deletedAt: timeLocal.now().toDate()
    });
    await deleteLog(req, data);
};