import {
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  Body,
  Param,
  Query,
  UseGuards,
} from "@nestjs/common";
import { Throttle } from "@nestjs/throttler";
import { CredentialsService } from "./credentials.service";
import {
  CreateCredentialDto,
  UpdateCredentialDto,
  RotateCredentialDto,
  QueryCredentialDto,
  QueryCredentialAuditDto,
} from "./dto";
import { AuthGuard } from "../auth/guards/auth.guard";
import { WorkspaceGuard, PermissionGuard } from "../common/guards";
import { Workspace, Permission, RequirePermission } from "../common/decorators";
import { CurrentUser } from "../auth/decorators/current-user.decorator";
import type { AuthenticatedUser } from "../common/types/user.types";

/**
 * Controller for user credential endpoints
 * All endpoints require authentication and workspace context
 *
 * Guards are applied in order:
 * 1. AuthGuard - Verifies user authentication
 * 2. WorkspaceGuard - Validates workspace access and sets RLS context
 * 3. PermissionGuard - Checks role-based permissions
 *
 * Security:
 * - List/Get endpoints NEVER return plaintext values (only maskedValue)
 * - getValue endpoint is intentionally separate and rate-limited
 * - All operations are audit-logged via ActivityService
 */
@Controller("credentials")
@UseGuards(AuthGuard, WorkspaceGuard, PermissionGuard)
export class CredentialsController {
  constructor(private readonly credentialsService: CredentialsService) {}

  /**
   * POST /api/credentials
   * Create a new credential
   * Requires: MEMBER role or higher
   */
  @Post()
  @RequirePermission(Permission.WORKSPACE_MEMBER)
  async create(
    @Body() createDto: CreateCredentialDto,
    @Workspace() workspaceId: string,
    @CurrentUser() user: AuthenticatedUser
  ) {
    return this.credentialsService.create(workspaceId, user.id, createDto);
  }

  /**
   * GET /api/credentials/audit
   * Get credential audit logs with optional filters
   * Shows all credential-related activities for the workspace
   * Requires: Any workspace member (including GUEST)
   */
  @Get("audit")
  @RequirePermission(Permission.WORKSPACE_ANY)
  async getAuditLog(@Query() query: QueryCredentialAuditDto, @Workspace() workspaceId: string) {
    return this.credentialsService.getAuditLog(workspaceId, query);
  }

  /**
   * GET /api/credentials
   * Get paginated credentials with optional filters
   * NEVER returns plaintext values - only maskedValue
   * Requires: Any workspace member (including GUEST)
   */
  @Get()
  @RequirePermission(Permission.WORKSPACE_ANY)
  async findAll(
    @Query() query: QueryCredentialDto,
    @Workspace() workspaceId: string,
    @CurrentUser() user: AuthenticatedUser
  ) {
    return this.credentialsService.findAll(workspaceId, user.id, query);
  }

  /**
   * GET /api/credentials/:id
   * Get a single credential by ID
   * NEVER returns plaintext value - only maskedValue
   * Requires: Any workspace member
   */
  @Get(":id")
  @RequirePermission(Permission.WORKSPACE_ANY)
  async findOne(
    @Param("id") id: string,
    @Workspace() workspaceId: string,
    @CurrentUser() user: AuthenticatedUser
  ) {
    return this.credentialsService.findOne(id, workspaceId, user.id);
  }

  /**
   * GET /api/credentials/:id/value
   * Decrypt and return credential value
   * CRITICAL: This is the ONLY endpoint that returns plaintext
   * Rate limited to 10 requests per minute per user
   * Logs access to activity log
   * Requires: Any workspace member
   */
  @Get(":id/value")
  @RequirePermission(Permission.WORKSPACE_ANY)
  @Throttle({ strict: { limit: 10, ttl: 60000 } })
  async getValue(
    @Param("id") id: string,
    @Workspace() workspaceId: string,
    @CurrentUser() user: AuthenticatedUser
  ) {
    return this.credentialsService.getValue(id, workspaceId, user.id);
  }

  /**
   * PATCH /api/credentials/:id
   * Update credential metadata (NOT the value itself)
   * Use /rotate endpoint to change the credential value
   * Requires: MEMBER role or higher
   */
  @Patch(":id")
  @RequirePermission(Permission.WORKSPACE_MEMBER)
  async update(
    @Param("id") id: string,
    @Body() updateDto: UpdateCredentialDto,
    @Workspace() workspaceId: string,
    @CurrentUser() user: AuthenticatedUser
  ) {
    return this.credentialsService.update(id, workspaceId, user.id, updateDto);
  }

  /**
   * POST /api/credentials/:id/rotate
   * Replace credential value with new encrypted value
   * Requires: MEMBER role or higher
   */
  @Post(":id/rotate")
  @RequirePermission(Permission.WORKSPACE_MEMBER)
  async rotate(
    @Param("id") id: string,
    @Body() rotateDto: RotateCredentialDto,
    @Workspace() workspaceId: string,
    @CurrentUser() user: AuthenticatedUser
  ) {
    return this.credentialsService.rotate(id, workspaceId, user.id, rotateDto.newValue);
  }

  /**
   * DELETE /api/credentials/:id
   * Soft-delete credential (set isActive = false)
   * Requires: MEMBER role or higher
   */
  @Delete(":id")
  @RequirePermission(Permission.WORKSPACE_MEMBER)
  async remove(
    @Param("id") id: string,
    @Workspace() workspaceId: string,
    @CurrentUser() user: AuthenticatedUser
  ) {
    return this.credentialsService.remove(id, workspaceId, user.id);
  }
}
