import {
  Body,
  Controller,
  Get,
  Param,
  Post,
  Query,
} from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { ZodResponse } from 'nestjs-zod';
import { Permission } from '@pac/types';
import {
  CurrentUser,
  AuthenticatedUser,
} from '../../common/decorators/current-user.decorator';
import { RequirePermission } from '../../common/decorators/permissions.decorator';
import {
  TenantScope,
  TenantScopeContext,
} from '../../common/decorators/tenant-scope.decorator';
import {
  AssignPlanRequestDto,
  ListPlansQueryDto,
  ListPlansResponseDto,
  PlanCountsResponseDto,
  PlanActionAckDto,
  PlanDetailResponseDto,
  RecomputeAckDto,
  RecyclePlanRequestDto,
  SubmitExecutionRequestDto,
  SubmitExecutionResponseDto,
  ListExecutionsResponseDto,
} from './dto/plan.dto';
import { PlanService } from './plan.service';
import { PlanEngineService } from './engine/plan-engine.service';
import { resolveScriptAgent } from '../ai/calls/draft-plan-script/shared/agent-identity';

@ApiTags('plan')
@ApiBearerAuth('accessToken')
@Controller('plans')
export class PlanController {
  constructor(
    private readonly plans: PlanService,
    private readonly engine: PlanEngineService,
  ) {}

  @Get()
  @ZodResponse({ status: 200, type: ListPlansResponseDto })
  @RequirePermission(Permission.PLAN_VIEW_OWN)
  @ApiOperation({
    summary: 'List plans (recall pool, my queue, or by filters)',
    description:
      'Use ?view=pool to fetch the unassigned active pool, ?view=mine for my assigned plans, ' +
      '?view=all for everything (subject to permission). Without view, staff sees own only.',
  })
  list(
    @TenantScope() scope: TenantScopeContext,
    @CurrentUser() user: AuthenticatedUser,
    @Query() query: ListPlansQueryDto,
  ) {
    return this.plans.list(scope, query, user.permissions);
  }

  @Get('counts')
  @ZodResponse({ status: 200, type: PlanCountsResponseDto })
  @RequirePermission(Permission.PLAN_VIEW_OWN)
  @ApiOperation({
    summary: 'Plan counts for KPI / tab badges (one SQL roundtrip, replaces 5 list calls)',
  })
  counts(
    @TenantScope() scope: TenantScopeContext,
    @CurrentUser() user: AuthenticatedUser,
  ) {
    return this.plans.counts(scope, user.permissions);
  }

  @Get(':id')
  @ZodResponse({ status: 200, type: PlanDetailResponseDto })
  @RequirePermission(Permission.PLAN_VIEW_OWN)
  detail(
    @TenantScope() scope: TenantScopeContext,
    @CurrentUser() user: AuthenticatedUser,
    @Param('id') id: string,
  ) {
    // 话术里的【回访客服】按当前登录人回填(见 agent-identity.ts)
    return this.plans.detail(scope, id, resolveScriptAgent(user));
  }

  @Post(':id/assign')
  @ZodResponse({ status: 200, type: PlanActionAckDto })
  @RequirePermission(Permission.PLAN_ASSIGN)
  async assign(
    @TenantScope() scope: TenantScopeContext,
    @Param('id') id: string,
    @Body() dto: AssignPlanRequestDto,
  ) {
    await this.plans.assign(scope, id, dto.assigneeUserId);
    return { ok: true as const };
  }

  @Post(':id/recycle')
  @ZodResponse({ status: 200, type: PlanActionAckDto })
  @RequirePermission(Permission.PLAN_RECYCLE)
  async recycle(
    @TenantScope() scope: TenantScopeContext,
    @Param('id') id: string,
    @Body() _dto: RecyclePlanRequestDto,
  ) {
    await this.plans.recycle(scope, id);
    return { ok: true as const };
  }

  @Post(':id/executions')
  @ZodResponse({ status: 201, type: SubmitExecutionResponseDto })
  @RequirePermission(Permission.PLAN_EXECUTE)
  @ApiOperation({
    summary:
      '接口 2: write a Plan execution outcome. Strict invariant — execution feedback ' +
      'NEVER promotes to PatientFactEvent.',
  })
  submitExecution(
    @TenantScope() scope: TenantScopeContext,
    @CurrentUser() user: AuthenticatedUser,
    @Param('id') id: string,
    @Body() dto: SubmitExecutionRequestDto,
  ) {
    return this.plans.submitExecution(scope, id, user.sub, dto);
  }

  @Get(':id/executions')
  @ZodResponse({ status: 200, type: ListExecutionsResponseDto })
  @RequirePermission(Permission.PLAN_VIEW_OWN)
  @ApiOperation({ summary: '某 plan 的执行历史(给"通话记录"面板)' })
  listExecutions(
    @TenantScope() scope: TenantScopeContext,
    @Param('id') id: string,
  ) {
    return this.plans.listExecutions(scope, id);
  }

  @Post(':id/recompute')
  @ZodResponse({ status: 202, type: RecomputeAckDto })
  @RequirePermission(Permission.PLAN_ASSIGN)
  @ApiOperation({
    summary: 'Force a plan recompute for the patient owning this plan (ops/dev tool)',
  })
  async recompute(@TenantScope() scope: TenantScopeContext, @Param('id') id: string) {
    const plan = await this.plans.detail(scope, id);
    const result = await this.engine.recomputeForPatient({
      hostId: scope.hostId,
      tenantId: scope.tenantId,
      // 新 schema:Plan 没 clinicId 字段;target_clinic_id 可空(集团统一池场景)
      clinicId: plan.plan.targetClinicId ?? '',
      patientId: plan.plan.patientId,
    });
    return { accepted: true as const, plansCreated: result.plansCreated };
  }

  @Post('recompute/by-patient/:patientId')
  @ZodResponse({ status: 202, type: RecomputeAckDto })
  @RequirePermission(Permission.PLAN_ASSIGN)
  @ApiOperation({
    summary: 'Recompute plans for a patient that has no plan yet (ops/dev cold-start tool)',
  })
  async recomputeByPatient(
    @TenantScope() scope: TenantScopeContext,
    @Param('patientId') patientId: string,
  ) {
    const result = await this.plans.recomputeByPatient(scope, patientId, this.engine);
    return { accepted: true as const, plansCreated: result.plansCreated };
  }
}
