import { Body, Controller, Get, Post, Req } from "@nestjs/common";
import type { Request } from "express";
import { IamService } from "./iam.service.js";
import type { TokenPair, UserInfo } from "./iam.service.js";
import { registerSchema, loginSchema, refreshTokenSchema } from "./iam.dto.js";
import { UnauthorizedError } from "../shared/errors/application-error.js";
import {
  Permissions,
  RequirePermission,
} from "../middleware/permission.guard.js";

@Controller("iam")
export class IamController {
  constructor(private readonly service: IamService) {}

  // 公开端点：注册，不设权限校验
  @Post("register")
  async register(
    @Body() body: unknown,
  ): Promise<{ success: true; data: { user: UserInfo; tokens: TokenPair } }> {
    const dto = registerSchema.parse(body);
    const result = await this.service.register(dto);
    return { success: true as const, data: result };
  }

  // 公开端点：登录，不设权限校验
  @Post("login")
  async login(
    @Body() body: unknown,
  ): Promise<{ success: true; data: { user: UserInfo; tokens: TokenPair } }> {
    const dto = loginSchema.parse(body);
    const result = await this.service.login(dto);
    return { success: true as const, data: result };
  }

  // 公开端点：刷新令牌，不设权限校验
  @Post("refresh")
  async refresh(
    @Body() body: unknown,
  ): Promise<{ success: true; data: TokenPair }> {
    const dto = refreshTokenSchema.parse(body);
    const tokens = await this.service.refresh(dto.refreshToken);
    return { success: true as const, data: tokens };
  }

  @Get("me")
  @RequirePermission(Permissions.IAM_USER_READ)
  async me(@Req() req: Request): Promise<{ success: true; data: UserInfo }> {
    const userIdHeader = req.headers["x-user-id"];
    const userId = typeof userIdHeader === "string" ? userIdHeader : undefined;
    if (!userId) {
      throw new UnauthorizedError("Missing x-user-id header");
    }
    const user = await this.service.getUserInfo(userId);
    return { success: true as const, data: user };
  }
}
