import {
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  Body,
  Param,
  Query,
  ParseUUIDPipe,
  HttpCode,
  HttpStatus,
  UseGuards,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiBearerAuth,
  ApiParam,
  ApiQuery,
} from '@nestjs/swagger';
import { CompaniesService } from './companies.service';
import { CreateCompanyDto } from './dto/create-company.dto';
import { UpdateCompanyDto } from './dto/update-company.dto';
import { QueryCompaniesDto } from './dto/query-companies.dto';
import { AddOwnerDto } from '../common/dto/owner.dto';
import { OwnersService } from '../owners/owners.service';
import { CurrentUser, JwtPayload } from '../common/decorators';
import { TenantGuard } from '../auth/guards/tenant.guard';
import {
  paginatedResponse,
  singleResponse,
} from '../common/dto/pagination.dto';

@ApiTags('Companies')
@ApiBearerAuth('access-token')
@UseGuards(TenantGuard)
@Controller('companies')
export class CompaniesController {
  constructor(
    private readonly companiesService: CompaniesService,
    private readonly ownersService: OwnersService,
  ) {}

  @Post()
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({ summary: 'Unternehmen erstellen' })
  async create(
    @CurrentUser() user: JwtPayload,
    @Body() dto: CreateCompanyDto,
  ) {
    const company = await this.companiesService.create(
      user.tenantId!,
      user.sub,
      dto,
    );
    return singleResponse(company);
  }

  @Get()
  @ApiOperation({ summary: 'Unternehmen auflisten (paginiert, suchbar)' })
  @ApiQuery({ name: 'page', required: false })
  @ApiQuery({ name: 'pageSize', required: false })
  @ApiQuery({ name: 'search', required: false })
  @ApiQuery({ name: 'industry', required: false })
  @ApiQuery({ name: 'sort', required: false })
  @ApiQuery({ name: 'order', required: false, enum: ['asc', 'desc'] })
  async findAll(
    @CurrentUser() user: JwtPayload,
    @Query() query: QueryCompaniesDto,
  ) {
    const result = await this.companiesService.findAll(
      user.tenantId!,
      query,
    );
    return paginatedResponse(
      result.data,
      result.total,
      result.page,
      result.pageSize,
    );
  }

  @Get(':id')
  @ApiOperation({
    summary: 'Unternehmensdetails (inkl. Kontakte und Deals)',
  })
  @ApiParam({ name: 'id', type: 'string', format: 'uuid' })
  async findOne(
    @CurrentUser() user: JwtPayload,
    @Param('id', ParseUUIDPipe) id: string,
  ) {
    const company = await this.companiesService.findOne(user.tenantId!, id);
    return singleResponse(company);
  }

  @Patch(':id')
  @ApiOperation({ summary: 'Unternehmen aktualisieren' })
  @ApiParam({ name: 'id', type: 'string', format: 'uuid' })
  async update(
    @CurrentUser() user: JwtPayload,
    @Param('id', ParseUUIDPipe) id: string,
    @Body() dto: UpdateCompanyDto,
  ) {
    const company = await this.companiesService.update(
      user.tenantId!,
      id,
      user.sub,
      dto,
    );
    return singleResponse(company);
  }

  @Delete(':id')
  @ApiOperation({ summary: 'Unternehmen loeschen' })
  @ApiParam({ name: 'id', type: 'string', format: 'uuid' })
  async remove(
    @CurrentUser() user: JwtPayload,
    @Param('id', ParseUUIDPipe) id: string,
  ) {
    const company = await this.companiesService.remove(user.tenantId!, id);
    return singleResponse(company);
  }

  // --------------------------------------------------------
  // Owner Endpoints
  // --------------------------------------------------------

  @Post(':id/owners')
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({ summary: 'Owner zu Unternehmen hinzufuegen' })
  @ApiParam({ name: 'id', type: 'string', format: 'uuid' })
  async addOwner(
    @CurrentUser() user: JwtPayload,
    @Param('id', ParseUUIDPipe) id: string,
    @Body() dto: AddOwnerDto,
  ) {
    const owner = await this.ownersService.addCompanyOwner(
      user.tenantId!,
      id,
      dto,
    );
    return singleResponse(owner);
  }

  @Delete(':id/owners/:userId')
  @ApiOperation({ summary: 'Owner von Unternehmen entfernen' })
  @ApiParam({ name: 'id', type: 'string', format: 'uuid' })
  @ApiParam({ name: 'userId', type: 'string', format: 'uuid' })
  async removeOwner(
    @CurrentUser() user: JwtPayload,
    @Param('id', ParseUUIDPipe) id: string,
    @Param('userId', ParseUUIDPipe) userId: string,
  ) {
    const owner = await this.ownersService.removeCompanyOwner(
      user.tenantId!,
      id,
      userId,
    );
    return singleResponse(owner);
  }
}
