import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { AdminGuard } from './admin.guard';
import { PrismaService } from '../../prisma/prisma.service';

@ApiTags('管理后台 - 用户管理')
@Controller('admin/users')
@UseGuards(AuthGuard('jwt'), AdminGuard)
@ApiBearerAuth()
export class UsersController {
  constructor(private prisma: PrismaService) {}

  @Get()
  async list(@Query('search') search?: string) {
    const where: any = {};
    if (search) {
      where.OR = [
        { nickname: { contains: search } },
        { phone: { contains: search } },
        { email: { contains: search } },
      ];
    }
    return {
      items: await this.prisma.user.findMany({
        where,
        select: {
          id: true, phone: true, nickname: true, email: true,
          status: true, memberPlan: true, createdAt: true,
        },
        orderBy: { id: 'desc' },
        take: 100,
      }),
    };
  }

  @Post()
  async create(@Body() body: { phone: string; nickname?: string; email?: string; password: string }) {
    const bcrypt = require('bcryptjs');
    const passwordHash = await bcrypt.hash(body.password, 10);
    return this.prisma.user.create({
      data: {
        phone: body.phone,
        nickname: body.nickname || '',
        email: body.email || '',
        passwordHash,
        status: 'ACTIVE',
      },
    });
  }

  @Put(':id')
  async update(@Param('id') id: string, @Body() body: { nickname?: string; email?: string; status?: string }) {
    const data: any = {};
    if (body.nickname !== undefined) data.nickname = body.nickname;
    if (body.email !== undefined) data.email = body.email;
    if (body.status) data.status = body.status;
    return this.prisma.user.update({ where: { id: parseInt(id) }, data });
  }

  @Delete(':id')
  async delete(@Param('id') id: string) {
    return this.prisma.user.update({
      where: { id: parseInt(id) },
      data: { deletedAt: new Date() },
    });
  }
}