import {
  Body,
  Controller,
  Delete,
  ForbiddenException,
  Get,
  Param,
  Patch,
  Post,
  Req,
  UnauthorizedException,
  UseGuards,
} from "@nestjs/common";
import { Request } from "express";
import { AuthService, CreateUserDto, JwtPayload, UpdateUserDto } from "./auth.service";
import { JwtAuthGuard } from "./jwt-auth.guard";

@Controller("auth")
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Post("login")
  async login(@Body() body: { email: string; password: string }) {
    if (!body.email || !body.password) {
      throw new UnauthorizedException("Email and password are required");
    }
    return this.authService.login(body.email, body.password);
  }

  @Get("me")
  @UseGuards(JwtAuthGuard)
  me(@Req() req: Request & { user: { sub: string } }) {
    return this.authService.findById(req.user.sub);
  }

  @Get("users")
  @UseGuards(JwtAuthGuard)
  listUsers(@Req() req: Request & { user: JwtPayload }) {
    this.ensureCanManageUsers(req.user);
    return this.authService.listUsers();
  }

  @Post("users")
  @UseGuards(JwtAuthGuard)
  createUser(@Req() req: Request & { user: JwtPayload }, @Body() body: CreateUserDto) {
    this.ensureCanManageUsers(req.user);
    return this.authService.createUser(body);
  }

  @Patch("users/:id")
  @UseGuards(JwtAuthGuard)
  updateUser(
    @Req() req: Request & { user: JwtPayload },
    @Param("id") id: string,
    @Body() body: UpdateUserDto,
  ) {
    this.ensureCanManageUsers(req.user);
    return this.authService.updateUser(id, body);
  }

  @Delete("users/:id")
  @UseGuards(JwtAuthGuard)
  deleteUser(@Req() req: Request & { user: JwtPayload }, @Param("id") id: string) {
    this.ensureCanManageUsers(req.user);
    if (req.user.sub === id) {
      throw new ForbiddenException("You cannot deactivate your own account");
    }
    return this.authService.deactivateUser(id);
  }

  private ensureCanManageUsers(user: JwtPayload) {
    if (user.role !== "store_manager" && user.role !== "super_admin") {
      throw new ForbiddenException("Only managers can manage users");
    }
  }
}
