const HospitalRepository = require('../../repository/admin/HospitalRepository.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 CityRepository = require('../../repository/admin/CityRepository.js');
const { BASE_URL } = require('../../../config/config.js');
const prisma = require('../../prisma/PrismaClient.js');
const { formatISOWithoutTimezone } = require('../../utils/FormatDate.js');

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

    const where = {
        ...SearchFilter(search, ['name', 'province.id', 'city.id', 'type', 'ownership', 'simrs_type']),
        ...(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([
        HospitalRepository.findAll({ skip, take: limit, where, orderBy: { [sortBy]: orderBy } }),
        HospitalRepository.countAll(where)
    ]);

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

    return { hospitals: formatted, total };
};

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

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

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 city = await CityRepository.findById(validateData.city_id);
    if (!city) {
        throw new HttpException('City not found', 404);
    }

    if (!req.file) {
        throw new HttpException({ image: ['image file is required'] }, 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);
    }

    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 HospitalRepository.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 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 HospitalRepository.update(id, payload);
    await updateLog(req, data);
};

exports.deleteHospitalService = async (id, req) => {
    const hospital = await HospitalRepository.findById(id);

    if (!hospital) {
        throw new HttpException('Hospital not found', 404);
    }

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

    await deleteLog(req, data);
};