const AdminRepository = require('../../repository/superadmin/AdminRepository.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');

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

    const where = {
        ...SearchFilter(search, ['username', 'email', 'firstname', 'lastname']),
        deletedAt: null
    };

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

    return { admin, total };
};

exports.showAdminService = async (id) => {
    const admin = await AdminRepository.AdminRepository.findById(id);
    if (!admin) {
        throw new HttpException("Data Admin not found", 404);
    }
    return admin;
};

exports.storeAdminService = async (userData, req) => {
    const userId = await AdminRepository.KeycloakRepository.createUser(userData);
    await AdminRepository.KeycloakRepository.assignAdminRole(userId);
    const data = await AdminRepository.AdminRepository.createUser(userId, userData);

    await createLog(req, data);
};

exports.updateAdminService = async (userData, id, req) => {
    const admin = await AdminRepository.AdminRepository.findById(id);
    if (!admin) throw new HttpException('Admin not found', 404);

    await AdminRepository.KeycloakRepository.updateUser(id, userData);
    const data = await AdminRepository.AdminRepository.updateUser(id, userData);

    await updateLog(req, data);
};

exports.deleteAdminService = async (id, req) => {
    const admin = await AdminRepository.AdminRepository.findById(id);
    if (!admin) {
        throw new HttpException('Admin not found', 404);
    }

    await AdminRepository.KeycloakRepository.deleteUser(id);
    const data = await AdminRepository.AdminRepository.deleteUser(id, { deletedAt: timeLocal.now().toDate() });

    await deleteLog(req, data);
};