const licenceRepository = require("../repositories/licenceRepository") const logger = require("../modules/logger") const { DefaultError } = require("../errors/errors") async function create({ key, productId, targetChannel }) { const existing = licenceRepository.findByKey(key) if (existing) { throw new DefaultError(409, "License key already exists.") } try { return licenceRepository.create(key, productId, targetChannel) } catch (error) { logger.error(error, ["Service", "yellow", "LICENSE", "green"]) throw new DefaultError(500, "Please contact the maintainer") } } function getLicenseByKey(key) { try { const license = licenceRepository.findByKey(key) if (!license) { throw new DefaultError(404, "License not found.") } return license } catch (error) { if (error instanceof DefaultError) throw error logger.error(error, ["Service", "yellow", "LICENSE", "green"]) throw new DefaultError(500, "Please contact the maintainer") } } async function updateStatus(id, status) { try { const result = licenceRepository.updateStatus(id, status) if (result.changes === 0) { throw new DefaultError(404, "License not found, status update failed.") } return result } catch (error) { if (error instanceof DefaultError) throw error logger.error(error, ["Service", "yellow", "LICENSE", "green"]) throw new DefaultError(500, "Please contact the maintainer") } } function listByProduct(productId) { try { const licenses = licenceRepository.findByProduct(productId) return licenses } catch (error) { logger.error(error, ["Service", "yellow", "LICENSE", "green"]) throw new DefaultError(500, "Please contact the maintainer") } } async function remove(id) { try { const result = licenceRepository.remove(id) if (result.changes === 0) { throw new DefaultError(404, "License not found.") } return result } catch (error) { if (error instanceof DefaultError) throw error logger.error(error, ["Service", "yellow", "LICENSE", "green"]) throw new DefaultError(500, "Please contact the maintainer") } } module.exports = { create, getLicenseByKey, updateStatus, listByProduct, remove }