const salesHospitalRepository = require('../../repository/sales/HospitalRepository.js');
const { SearchFilter } = require('../../utils/SearchFilter.js');
const prisma = require('../../prisma/PrismaClient.js');
const { createLog, updateLog } = require('../../utils/LogActivity.js');
const ProvinceRepository = require('../../repository/admin/ProvinceRepository.js');
const CityRepository = require('../../repository/admin/CityRepository.js');
const HttpException = require('../../utils/HttpException.js');
const HospitalRepository = require('../../repository/admin/HospitalRepository.js');
const { formatISOWithoutTimezone } = require('../../utils/FormatDate.js');

exports.getAllHospitalByAreaService = async ({ page, limit, search, sortBy, orderBy, province, city, type, ownership, progress_status }, req) => {
    const skip = (page - 1) * limit;

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

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

    const where = {
        ...SearchFilter(search, ['name', 'province.id', 'city.id', 'type', 'ownership', 'simrs_type']),
        province_id: { in: provinceIds },
        ...(province ? { province_id: province } : {}),
        ...(city ? { city_id: city } : {}),
        ...(type ? { type: type } : {}),
        ...(ownership ? { ownership: ownership } : {}),
        ...(progress_status ? { progress_status: progress_status } : {}),
        deletedAt: null
    };

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

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

    return { hospitals: formatted, total };
};

// exports.getAllHospitalByAreaService = async (
//     { page, limit, search, sortBy, orderBy, province, city, type, ownership, progress_status },
//     req
// ) => {
//     const skip = (page - 1) * limit;

//     // 1. Ambil daftar provinsi yang dimiliki user
//     const userAreas = await prisma.userArea.findMany({
//         where: {
//             user_id: req.user.id,
//             deletedAt: null,
//         },
//         select: { province_id: true },
//     });

//     const areaProvinceIds = userAreas.map((ua) => ua.province_id);

//     if (areaProvinceIds.length === 0) {
//         return { hospitals: [], total: 0 };
//     }

//     // 2. Bangun filter where
//     const where = {
//         ...SearchFilter(search, [
//             'name',
//             'province.name',
//             'city.name',
//             'type',
//             'ownership',
//             'simrs_type',
//         ]),
//         province_id: province
//             ? province // jika user filter 1 provinsi → override area
//             : { in: areaProvinceIds }, // kalau tidak → gunakan semua area user
//         ...(city ? { city_id: city } : {}),
//         ...(type ? { type } : {}),
//         ...(ownership ? { ownership } : {}),
//         ...(progress_status ? { progress_status } : {}),
//         deletedAt: null,
//     };

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

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

//     return { hospitals: formatted, total };
// };

exports.storeHospitalService = async (validateData, req) => {
    const creatorId = req.user.id;

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

    const userArea = await prisma.userArea.findFirst({
        where: {
            user_id: req.user.id,
            province_id: validateData.province_id
        }
    });

    if (!userArea) {
        throw new HttpException('You are not allowed to add hospital to this province', 403);
    }

    const city = await CityRepository.findById(validateData.city_id);
    if (!city) {
        throw new HttpException('City not found', 404);
    }

    const existingHospital = await prisma.hospital.findFirst({
        where: {
            name: validateData.name,
            city_id: validateData.city_id,
            deletedAt: null
        }
    });

    if (existingHospital) {
        throw new HttpException('Hospital with same name in this city already exists', 400);
    }

    if (!req.file) {
        throw new HttpException({ image: ['image file is required'] }, 422);
    }

    const imagePath = req.file ? `/storage/img/${req.file.filename}` : null;

    const payload = {
        ...validateData,
        image: imagePath,
        progress_status: "cari_data",
        simrs_type: "-",
        created_by: creatorId
    };

    const data = await salesHospitalRepository.create(payload);
    await createLog(req, data);
};

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

exports.updateHospitalService = async (validateData, id, req) => {
    const hospital = await HospitalRepository.findById(id);
    if (!hospital) {
        throw new HttpException("Hospital data not found", 404);
    }

    const userArea = await prisma.userArea.findFirst({
        where: {
            user_id: req.user.id,
            province_id: validateData.province_id
        }
    });

    if (!userArea) {
        throw new HttpException("You are not authorized to update hospital in this province", 403);
    }

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

    const city = await CityRepository.findById(validateData.city_id);
    if (!city) {
        throw new HttpException('City not found', 404);
    }

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

    const existingHospital = await prisma.hospital.findFirst({
        where: {
            name: validateData.name,
            city_id: validateData.city_id,
            deletedAt: null
        }
    });

    if (existingHospital) {
        throw new HttpException('Hospital with same name in this city already exists', 400);
    }

    // Jika ada file baru, replace image
    let imagePath = hospital.image; // pakai yang lama
    if (req.file) {
        imagePath = `/storage/img/${req.file.filename}`; // path relatif
    }

    const payload = {
        ...validateData,
        image: imagePath,
        // created_by: req.user.id,
    };

    const data = await salesHospitalRepository.update(id, payload);
    await updateLog(req, data);
};

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

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