import {
  Controller,
  Post,
  Get,
  Param,
  NotFoundException,
  ServiceUnavailableException,
} from '@nestjs/common';
import { DingTalkRouterService } from '../../../infrastructure/dingtalk/dingtalk-router.service';
import { AgentInstanceRepository } from '../../../infrastructure/repositories/agent-instance.repository';

@Controller('api/v1/agent/channels')
export class AgentChannelController {
  constructor(
    private readonly dingTalkRouter: DingTalkRouterService,
    private readonly instanceRepo: AgentInstanceRepository,
  ) {}

  /** Generate a 6-char binding code for the given agent instance */
  @Post('dingtalk/bind/:instanceId')
  async generateBindCode(@Param('instanceId') instanceId: string) {
    if (!this.dingTalkRouter.isEnabled()) {
      throw new ServiceUnavailableException('DingTalk integration not configured on this server');
    }
    const inst = await this.instanceRepo.findById(instanceId);
    if (!inst) throw new NotFoundException(`Instance ${instanceId} not found`);

    const { code, expiresAt } = this.dingTalkRouter.generateBindingCode(instanceId);
    return { code, expiresAt };
  }

  /** Check if the given instance is already bound to a DingTalk user */
  @Get('dingtalk/status/:instanceId')
  async getBindStatus(@Param('instanceId') instanceId: string) {
    const inst = await this.instanceRepo.findById(instanceId);
    if (!inst) throw new NotFoundException(`Instance ${instanceId} not found`);
    return { bound: !!inst.dingTalkUserId };
  }

  /** Unbind the DingTalk user from the given agent instance */
  @Post('dingtalk/unbind/:instanceId')
  async unbind(@Param('instanceId') instanceId: string) {
    const inst = await this.instanceRepo.findById(instanceId);
    if (!inst) throw new NotFoundException(`Instance ${instanceId} not found`);
    inst.dingTalkUserId = undefined;
    await this.instanceRepo.save(inst);
    return { unbound: true };
  }
}
