import { Controller, Get, Res, HttpStatus, Query } from '@nestjs/common'; import { WhatsappService } from '../whatsapp/whatsapp.service'; @Controller('get/groups') export class GroupController { constructor(private readonly whatsappService: WhatsappService) {} @Get('/') async getGroups(@Res() res: any) { try { const sock = this.whatsappService.getSocket(); const groups = await sock.groupFetchAllParticipating(); const formattedGroups = Object.values(groups).map((g) => ({ name: g.subject, jid: g.id, participants: g.participants.length, })); // Kirim respons sukses return res.status(HttpStatus.OK).json({ status: 'Success', data: formattedGroups, }); } catch (err: unknown) { const message = err instanceof Error ? err.message : 'Unknown error'; console.error('Gagal mengambil data grup:', message); const cachedGroups = this.whatsappService.getAllGroupsCache(); if (cachedGroups.length > 0) { return res.status(HttpStatus.OK).json({ status: 'Success (Cached)', data: cachedGroups, }); } return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ status: 'Error', message: 'Gagal mengambil grup dan cache kosong: ' + message, }); } } @Get('id') async getGroupId( @Query('name') name: string, @Query('jid') jid: string, @Res() res: any, ) { try { if (jid) { return res.status(HttpStatus.OK).json({ status: 'Success', data: { jid } }); } if (!name) { return res.status(HttpStatus.BAD_REQUEST).json({ status: 'Error', message: 'Query `name` atau `jid` diperlukan.' }); } const cached = this.whatsappService.getAllGroupsCache(); const matches = cached.filter((g) => g.name && g.name.toLowerCase().includes(name.toLowerCase())); if (matches.length > 0) { return res.status(HttpStatus.OK).json({ status: 'Success', data: matches }); } return res.status(HttpStatus.NOT_FOUND).json({ status: 'NotFound', message: 'Tidak ditemukan grup yang cocok.' }); } catch (err: unknown) { const message = err instanceof Error ? err.message : 'Unknown error'; console.error('Gagal mencari ID grup:', message); return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ status: 'Error', message }); } } }