const HttpException = require('../../utils/HttpException.js');
const prisma = require('../../prisma/PrismaClient.js');
const { createLog } = require('../../utils/LogActivity.js');
const StatusHistoryRepository = require('../../repository/sales/StatusHistoryRepository.js');

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

    const userId = req.user.id;
    const hospitalId = req.params.id;
    const hospital = await prisma.hospital.findFirst({
        where: {
            id: hospitalId
        }
    })
    if (!hospital) {
        throw new HttpException("Hospital not found", 404)
    }

    const userAreas = await prisma.userArea.findMany({
        where: { user_id: userId },
        select: { province_id: true }
    });

    const userProvinceIds = userAreas.map(ua => ua.province_id);

    if (!userProvinceIds.includes(hospital.province_id)) {
        throw new HttpException("This hospital is not your area", 403);
    }

    const where = {
        hospital_id: req.params.id,
        deletedAt: null
    };

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

    return { status_histories, total };
};

const validProgressStatuses = ['cari_data', 'dihubungi', 'negosiasi', 'follow_up', 'mou', 'onboarded', 'tidak_berminat'];

exports.storeStatusHistoryService = async (validateData, req) => {
    const hospitalId = req.params.id;
    const userId = req.user.id;

    const hospital = await prisma.hospital.findFirst({
        where: {
            id: hospitalId
        }
    })
    if (!hospital) {
        throw new HttpException("Hospital not found", 404)
    }

    const userAreas = await prisma.userArea.findMany({
        where: { user_id: userId },
        select: { province_id: true }
    });

    const userProvinceIds = userAreas.map(ua => ua.province_id);

    if (!userProvinceIds.includes(hospital.province_id)) {
        throw new HttpException("This hospital is not your area", 403);
    }

    if (validateData.new_status && !validProgressStatuses.includes(validateData.new_status)) {
        throw new HttpException(
            `Invalid new_status. Allowed values are: ${validProgressStatuses.join(', ')}`,
            422
        );
    }

    if (validateData.new_status === hospital.progress_status) {
        throw new HttpException("New status change is the same as old status", 400)
    }

    const payload = {
        hospital_id: hospitalId,
        user_id: userId,
        old_status: hospital.progress_status,
        new_status: validateData.new_status,
        note: validateData.note,
    };

    const data = await StatusHistoryRepository.create(payload);

    await prisma.hospital.update({
        where: { id: hospitalId },
        data: {
            progress_status: validateData.new_status
        }
    });

    await createLog(req, data);
};