import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  Query,
  UseGuards,
  Req,
  HttpCode,
  HttpStatus,
  ParseUUIDPipe,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { JwtAuthGuard, RolesGuard, Roles, UserRole } from '@genex/common';
import { AnnouncementService } from '../../../application/services/announcement.service';
import { UserTagService } from '../../../application/services/user-tag.service';
import {
  CreateAnnouncementDto,
  UpdateAnnouncementDto,
  ListAnnouncementsQueryDto,
  UserAnnouncementsQueryDto,
} from '../dto/announcement.dto';
import { AddTagDto, RemoveTagsDto, SyncTagsDto } from '../dto/user-tag.dto';

// ──────────────────────────────────────────────
//  Admin Announcement Controller
// ──────────────────────────────────────────────

@ApiTags('Admin - Announcements')
@Controller('admin/announcements')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(UserRole.ADMIN)
@ApiBearerAuth()
export class AdminAnnouncementController {
  constructor(private readonly announcementService: AnnouncementService) {}

  @Post()
  @ApiOperation({ summary: 'Create announcement with targeting (ALL / BY_TAG / SPECIFIC)' })
  async create(@Body() dto: CreateAnnouncementDto, @Req() req: any) {
    const announcement = await this.announcementService.create({
      title: dto.title,
      content: dto.content,
      type: dto.type,
      priority: dto.priority,
      targetType: dto.targetType,
      targetConfig: dto.targetConfig,
      imageUrl: dto.imageUrl,
      linkUrl: dto.linkUrl,
      publishedAt: dto.publishedAt ? new Date(dto.publishedAt) : undefined,
      expiresAt: dto.expiresAt ? new Date(dto.expiresAt) : undefined,
      createdBy: req.user?.id,
    });
    return { code: 0, data: announcement };
  }

  @Get()
  @ApiOperation({ summary: 'List announcements (admin)' })
  async findAll(@Query() query: ListAnnouncementsQueryDto) {
    const result = await this.announcementService.findAll({
      type: query.type,
      isEnabled: query.isEnabled,
      page: query.page,
      limit: query.limit,
    });
    return { code: 0, data: result };
  }

  @Get(':id')
  @ApiOperation({ summary: 'Get announcement detail' })
  async findOne(@Param('id', ParseUUIDPipe) id: string) {
    const announcement = await this.announcementService.findById(id);
    return { code: 0, data: announcement };
  }

  @Put(':id')
  @ApiOperation({ summary: 'Update announcement' })
  async update(
    @Param('id', ParseUUIDPipe) id: string,
    @Body() dto: UpdateAnnouncementDto,
  ) {
    const announcement = await this.announcementService.update(id, {
      title: dto.title,
      content: dto.content,
      type: dto.type,
      priority: dto.priority,
      targetType: dto.targetType,
      targetConfig: dto.targetConfig,
      imageUrl: dto.imageUrl,
      linkUrl: dto.linkUrl,
      isEnabled: dto.isEnabled,
      publishedAt: dto.publishedAt !== undefined
        ? dto.publishedAt ? new Date(dto.publishedAt) : null
        : undefined,
      expiresAt: dto.expiresAt !== undefined
        ? dto.expiresAt ? new Date(dto.expiresAt) : null
        : undefined,
    });
    return { code: 0, data: announcement };
  }

  @Delete(':id')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Delete announcement' })
  async delete(@Param('id', ParseUUIDPipe) id: string) {
    await this.announcementService.delete(id);
    return { code: 0, data: null };
  }
}

// ──────────────────────────────────────────────
//  Admin User Tag Controller
// ──────────────────────────────────────────────

@ApiTags('Admin - User Tags')
@Controller('admin/user-tags')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(UserRole.ADMIN)
@ApiBearerAuth()
export class AdminUserTagController {
  constructor(private readonly userTagService: UserTagService) {}

  @Get()
  @ApiOperation({ summary: 'List all tags with user count' })
  async getAllTags() {
    return { code: 0, data: await this.userTagService.getAllTags() };
  }

  @Get(':userId')
  @ApiOperation({ summary: 'Get tags for a specific user' })
  async getUserTags(@Param('userId', ParseUUIDPipe) userId: string) {
    return { code: 0, data: await this.userTagService.getTagsByUserId(userId) };
  }

  @Post(':userId')
  @ApiOperation({ summary: 'Add a tag to a user' })
  async addTag(
    @Param('userId', ParseUUIDPipe) userId: string,
    @Body() dto: AddTagDto,
  ) {
    await this.userTagService.addTag(userId, dto.tag);
    return { code: 0, data: null };
  }

  @Delete(':userId')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Remove tags from a user' })
  async removeTags(
    @Param('userId', ParseUUIDPipe) userId: string,
    @Body() dto: RemoveTagsDto,
  ) {
    await this.userTagService.removeTags(userId, dto.tags);
    return { code: 0, data: null };
  }

  @Put(':userId/sync')
  @ApiOperation({ summary: 'Sync (replace all) user tags' })
  async syncTags(
    @Param('userId', ParseUUIDPipe) userId: string,
    @Body() dto: SyncTagsDto,
  ) {
    await this.userTagService.syncTags(userId, dto.tags);
    return { code: 0, data: null };
  }
}

// ──────────────────────────────────────────────
//  User Announcement Controller (mobile/web)
// ──────────────────────────────────────────────

@ApiTags('Announcements')
@Controller('announcements')
@UseGuards(AuthGuard('jwt'))
@ApiBearerAuth()
export class UserAnnouncementController {
  constructor(private readonly announcementService: AnnouncementService) {}

  @Get()
  @ApiOperation({ summary: 'Get announcements for current user (filtered by targeting)' })
  async list(@Req() req: any, @Query() query: UserAnnouncementsQueryDto) {
    const result = await this.announcementService.getForUser(req.user.id, {
      type: query.type,
      page: query.page,
      limit: query.limit,
    });
    return { code: 0, data: result };
  }

  @Get('unread-count')
  @ApiOperation({ summary: 'Get unread announcement count' })
  async unreadCount(@Req() req: any) {
    const count = await this.announcementService.countUnreadForUser(req.user.id);
    return { code: 0, data: { count } };
  }

  @Put(':id/read')
  @ApiOperation({ summary: 'Mark announcement as read' })
  async markAsRead(@Param('id', ParseUUIDPipe) id: string, @Req() req: any) {
    await this.announcementService.markAsRead(id, req.user.id);
    return { code: 0, data: null };
  }

  @Put('read-all')
  @ApiOperation({ summary: 'Mark all announcements as read' })
  async markAllAsRead(@Req() req: any) {
    await this.announcementService.markAllAsRead(req.user.id);
    return { code: 0, data: null };
  }
}
