const VendorRepository = require('../../repository/sales/VendorRepository.js');
const HttpException = require('../../utils/HttpException.js');
const prisma = require('../../prisma/PrismaClient.js');
const { SearchFilter } = require('../../utils/SearchFilter.js');
const { formatISOWithoutTimezone, formatDateOnly } = require('../../utils/FormatDate.js');

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

    // 1. Ambil provinsi yang menjadi area kerja sales
    const userAreas = await prisma.userArea.findMany({
        where: {
            user_id: userId,
            deletedAt: null,
        },
        select: { province_id: true }
    });

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

    if (provinceIds.length === 0) {
        return { vendors: [], total: 0 };
    }

    // 2. Ambil vendor_id dari vendor_histories RS di provinsi tersebut
    const vendorHistories = await prisma.vendorHistory.findMany({
        where: {
            deletedAt: null,
            status: 'active',
            vendor_id: { not: null },
            hospital: {
                deletedAt: null,
                province_id: { in: provinceIds }
            }
        },
        select: { vendor_id: true },
        distinct: ['vendor_id']
    });

    const vendorIds = vendorHistories.map(v => v.vendor_id);

    // 3. Filter vendor berdasarkan hasil vendor_id
    const where = {
        ...SearchFilter(search, ['name', 'name_pt']),
        deletedAt: null,
        id: { in: vendorIds }
    };

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

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

    return { vendors: formatted, total };
};

// exports.showVendorService = async (id) => {
//     const vendor = await VendorRepository.findById(id);
//     if (!vendor) {
//         throw new HttpException("Data vendor not found", 404);
//     }
//     return vendor;
// };

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

//     const payload = {
//         ...validateData,
//         created_by: creatorId
//     };

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

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

//     const vendor = await VendorRepository.findById(id);
//     if (!vendor) {
//         throw new HttpException("Data vendor not found", 404);
//     }

//     const payload = {
//         ...validateData,
//         created_by: creatorId
//     };

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

// exports.deleteVendorService = async (id, req) => {
//     const vendor = await VendorRepository.findById(id);

//     if (!vendor) {
//         throw new HttpException('Vendor not found', 404);
//     }

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

//     await deleteLog(req, data);
// };