// ============================================================
// Lexware Office - Contacts REST Controller
// ============================================================

import {
  Controller,
  Get,
  Post,
  Delete,
  Body,
  Param,
  Query,
  ParseUUIDPipe,
  HttpCode,
  HttpStatus,
  UseGuards,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiBearerAuth,
  ApiParam,
} from '@nestjs/swagger';
import { TenantGuard } from '../auth/guards/tenant.guard';
import { CurrentUser, JwtPayload } from '../common/decorators';
import { singleResponse } from '../common/dto/pagination.dto';
import { LexwareContactsService } from './lexware-contacts.service';
import { SearchLexwareContactsDto } from './dto/search-lexware-contacts.dto';
import {
  LinkLexwareToCompanyDto,
  LinkLexwareToContactDto,
  ImportLexwareContactDto,
} from './dto/link-lexware-contact.dto';

@ApiTags('Lexware Office - Kontakte')
@ApiBearerAuth('access-token')
@UseGuards(TenantGuard)
@Controller('lexware/contacts')
export class LexwareContactsController {
  constructor(private readonly service: LexwareContactsService) {}

  @Get('search')
  @ApiOperation({
    summary: 'Lexware-Kontakte suchen (Proxy zu Lexware Office API)',
  })
  async search(@Query() query: SearchLexwareContactsDto) {
    const result = await this.service.searchContacts(query);
    return {
      success: true,
      data: result.content,
      pagination: {
        page: result.number + 1, // Lexware ist 0-basiert, CRM 1-basiert
        pageSize: result.size,
        total: result.totalElements,
        totalPages: result.totalPages,
      },
      meta: { timestamp: new Date().toISOString() },
    };
  }

  @Post('link-company')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({
    summary: 'Lexware-Kontakt mit CRM-Unternehmen verknuepfen',
  })
  async linkCompany(
    @CurrentUser() user: JwtPayload,
    @Body() dto: LinkLexwareToCompanyDto,
  ) {
    const result = await this.service.linkToCompany(
      user.tenantId!,
      dto.companyId,
      dto.lexwareContactId,
      user.sub,
    );
    return singleResponse(result);
  }

  @Post('link-contact')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({
    summary: 'Lexware-Kontakt mit CRM-Kontakt verknuepfen',
  })
  async linkContact(
    @CurrentUser() user: JwtPayload,
    @Body() dto: LinkLexwareToContactDto,
  ) {
    const result = await this.service.linkToContact(
      user.tenantId!,
      dto.contactId,
      dto.lexwareContactId,
      user.sub,
    );
    return singleResponse(result);
  }

  @Delete('unlink-company/:companyId')
  @ApiOperation({ summary: 'Lexware-Verknuepfung von Unternehmen loesen' })
  @ApiParam({ name: 'companyId', type: 'string', format: 'uuid' })
  async unlinkCompany(
    @CurrentUser() user: JwtPayload,
    @Param('companyId', ParseUUIDPipe) companyId: string,
  ) {
    const result = await this.service.unlinkCompany(
      user.tenantId!,
      companyId,
      user.sub,
    );
    return singleResponse(result);
  }

  @Delete('unlink-contact/:contactId')
  @ApiOperation({ summary: 'Lexware-Verknuepfung von Kontakt loesen' })
  @ApiParam({ name: 'contactId', type: 'string', format: 'uuid' })
  async unlinkContact(
    @CurrentUser() user: JwtPayload,
    @Param('contactId', ParseUUIDPipe) contactId: string,
  ) {
    const result = await this.service.unlinkContact(
      user.tenantId!,
      contactId,
      user.sub,
    );
    return singleResponse(result);
  }

  @Post('import-company')
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({
    summary: 'Neues CRM-Unternehmen aus Lexware-Kontakt erstellen',
  })
  async importCompany(
    @CurrentUser() user: JwtPayload,
    @Body() dto: ImportLexwareContactDto,
  ) {
    const result = await this.service.importAsCompany(
      user.tenantId!,
      dto.lexwareContactId,
      user.sub,
    );
    return singleResponse(result);
  }

  @Post('import-contact')
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({
    summary: 'Neuen CRM-Kontakt aus Lexware-Kontakt erstellen',
  })
  async importContact(
    @CurrentUser() user: JwtPayload,
    @Body() dto: ImportLexwareContactDto,
  ) {
    const result = await this.service.importAsContact(
      user.tenantId!,
      dto.lexwareContactId,
      user.sub,
    );
    return singleResponse(result);
  }

  @Post('push/:entityType/:entityId')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'CRM-Entity nach Lexware pushen (ERP)' })
  @ApiParam({ name: 'entityType', enum: ['company', 'contact'] })
  @ApiParam({ name: 'entityId', type: 'string', format: 'uuid' })
  async push(
    @CurrentUser() user: JwtPayload,
    @Param('entityType') entityType: string,
    @Param('entityId', ParseUUIDPipe) entityId: string,
  ) {
    if (entityType === 'company') {
      const result = await this.service.pushCompanyToLexware(
        user.tenantId!,
        entityId,
      );
      return singleResponse(result);
    } else {
      const result = await this.service.pushContactToLexware(
        user.tenantId!,
        entityId,
      );
      return singleResponse(result);
    }
  }

  @Post('sync/:entityType/:entityId')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({
    summary: 'Daten aus Lexware in CRM-Entity aktualisieren',
  })
  @ApiParam({ name: 'entityType', enum: ['company', 'contact'] })
  @ApiParam({ name: 'entityId', type: 'string', format: 'uuid' })
  async sync(
    @CurrentUser() user: JwtPayload,
    @Param('entityType') entityType: string,
    @Param('entityId', ParseUUIDPipe) entityId: string,
  ) {
    if (entityType === 'company') {
      const result = await this.service.syncCompanyFromLexware(
        user.tenantId!,
        entityId,
        user.sub,
      );
      return singleResponse(result);
    } else {
      const result = await this.service.syncContactFromLexware(
        user.tenantId!,
        entityId,
        user.sub,
      );
      return singleResponse(result);
    }
  }
}
