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

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

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

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

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

    return { cities: formatted, total };
};

exports.showCityService = async (id) => {
    const city = await CityRepository.findById(id);
    if (!city) {
        throw new HttpException("Data city not found", 404);
    }

    return {
        ...city,
        createdAt: formatISOWithoutTimezone(city.createdAt),
        updatedAt: formatISOWithoutTimezone(city.updatedAt),
    };
};

exports.storeCityService = async (validateData, req) => {
    const province = await ProvinceRepository.findById(validateData.province_id);
    if (!province) {
        throw new HttpException('Province not found', 404);
    }

    const data = await CityRepository.create(validateData);
    await createLog(req, data);
};

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

    const province = await ProvinceRepository.findById(validateData.province_id);
    if (!province) {
        throw new HttpException('Province not found', 404);
    }

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

exports.deleteCityService = async (id, req) => {
    const city = await CityRepository.findById(id);

    if (!city) {
        throw new HttpException('City not found', 404);
    }

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

    await deleteLog(req, data);
};