import {
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  Body,
  Param,
  Query,
  Req,
  UseGuards,
} from '@nestjs/common';
import { NotificationsService } from './notifications.service';
import { CreateConfigDto, UpdateConfigDto } from './dto/create-config.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { PushService } from './push.service';

@UseGuards(JwtAuthGuard)
@Controller('notifications')
export class NotificationsController {
  constructor(
    private readonly notificationsService: NotificationsService,
    private readonly pushService: PushService,
  ) {}

  // ── Notification endpoints ────────────────────────
  //
  // FIX (clients saw other people's notifications):
  //  • Client tokens carry the user id in `sub`, not `id` — read both.
  //  • Client-portal users only ever see notifications addressed to
  //    THEM (target_user_ids). Role-based notifications are for staff,
  //    so they are never matched for a client, even if the client's
  //    user account happens to have a row in user_roles.

  /** Logged-in user id from either a staff token (id) or a client token (sub). */
  private userId(req: any): number {
    return Number(req.user?.id ?? req.user?.sub ?? req.user?.userId);
  }

  /** True for client-portal tokens. */
  private isClient(req: any): boolean {
    const u = req.user ?? {};
    return (
      Number(u.is_client) === 1 ||
      (Array.isArray(u.roleNames) && u.roleNames.includes('Client'))
    );
  }

  @Get()
  async findAll(@Req() req: any, @Query('unread') unread?: string) {
    const unreadOnly = unread === 'true';
    return this.notificationsService.findAll(this.userId(req), unreadOnly, this.isClient(req));
  }

  @Get('unread-count')
  async getUnreadCount(@Req() req: any) {
    const count = await this.notificationsService.getUnreadCount(this.userId(req), this.isClient(req));
    return { count };
  }

  @Patch(':id/read')
  async markRead(@Param('id') id: string, @Req() req: any) {
    await this.notificationsService.markRead(+id, this.userId(req), this.isClient(req));
    return { success: true };
  }

  @Patch('mark-all-read')
  async markAllRead(@Req() req: any) {
    await this.notificationsService.markAllRead(this.userId(req), this.isClient(req));
    return { success: true };
  }

  // ── Config endpoints ──────────────────────────────

  @Get('config')
  async findAllConfigs() {
    return this.notificationsService.findAllConfigs();
  }

  @Post('config')
  async createConfig(@Body() dto: CreateConfigDto) {
    return this.notificationsService.createConfig(dto);
  }

  @Patch('config/:id')
  async updateConfig(@Param('id') id: string, @Body() dto: UpdateConfigDto) {
    await this.notificationsService.updateConfig(+id, dto);
    return { success: true };
  }

  @Delete('config/:id')
  async deleteConfig(@Param('id') id: string) {
    await this.notificationsService.deleteConfig(+id);
    return { success: true };
  }
  @Get('push/vapid-public-key')
  getVapidKey() {
    return { key: process.env.VAPID_PUBLIC_KEY };
  }

  @Post('push/subscribe')
  async pushSubscribe(@Req() req: any, @Body() body: any) {
    const userId = req.user?.id ?? req.user?.sub; // ✅ id first, sub as fallback
    console.log('📱 Push subscribe for user:', userId);
    await this.pushService.subscribe(userId, body);
    return { ok: true };
  }
}