import {
  Controller,
  Get,
  Post,
  Delete,
  Body,
  Param,
  ParseUUIDPipe,
  HttpCode,
  HttpStatus,
  UseGuards,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiBearerAuth,
  ApiParam,
} from '@nestjs/swagger';
import { CompanyRelationshipsService } from './company-relationships.service';
import { CreateRelationshipDto } from './dto/create-relationship.dto';
import { CurrentUser, JwtPayload } from '../common/decorators';
import { TenantGuard } from '../auth/guards/tenant.guard';
import { singleResponse } from '../common/dto/pagination.dto';

@ApiTags('Company Relationships')
@ApiBearerAuth('access-token')
@UseGuards(TenantGuard)
@Controller('companies/:companyId/relationships')
export class CompanyRelationshipsController {
  constructor(
    private readonly companyRelationshipsService: CompanyRelationshipsService,
  ) {}

  @Post()
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({ summary: 'Unternehmensbeziehung erstellen' })
  @ApiParam({ name: 'companyId', type: 'string', format: 'uuid' })
  async create(
    @CurrentUser() user: JwtPayload,
    @Param('companyId', ParseUUIDPipe) companyId: string,
    @Body() dto: CreateRelationshipDto,
  ) {
    const rel = await this.companyRelationshipsService.create(
      user.tenantId!,
      companyId,
      user.sub,
      dto,
    );
    return singleResponse(rel);
  }

  @Get()
  @ApiOperation({ summary: 'Beziehungen eines Unternehmens auflisten' })
  @ApiParam({ name: 'companyId', type: 'string', format: 'uuid' })
  async findAll(
    @CurrentUser() user: JwtPayload,
    @Param('companyId', ParseUUIDPipe) companyId: string,
  ) {
    const relationships = await this.companyRelationshipsService.findByCompany(
      user.tenantId!,
      companyId,
    );
    return { data: relationships };
  }

  @Delete(':relationshipId')
  @ApiOperation({ summary: 'Unternehmensbeziehung loeschen' })
  @ApiParam({ name: 'companyId', type: 'string', format: 'uuid' })
  @ApiParam({ name: 'relationshipId', type: 'string', format: 'uuid' })
  async remove(
    @CurrentUser() user: JwtPayload,
    @Param('companyId', ParseUUIDPipe) companyId: string,
    @Param('relationshipId', ParseUUIDPipe) relationshipId: string,
  ) {
    const rel = await this.companyRelationshipsService.remove(
      user.tenantId!,
      companyId,
      relationshipId,
    );
    return singleResponse(rel);
  }
}
