import {
  Controller, Get, Post, Patch, Delete,
  Param, Body, Query, HttpCode, HttpStatus,
} from '@nestjs/common'
import { WorkflowsService } from './workflows.service'
import { CreateWorkflowTemplateDto } from './dto/create-workflow-template.dto'
import { UpdateWorkflowTemplateDto } from './dto/update-workflow-template.dto'
import { InstantiateWorkflowDto } from './dto/instantiate-workflow.dto'
import { UpdateStepDto } from './dto/update-step.dto'

// ── Template endpoints ─────────────────────────────────────────────────────────

@Controller('workflow-templates')
export class WorkflowTemplatesController {
  constructor(private readonly svc: WorkflowsService) {}

  @Post()
  create(@Body() dto: CreateWorkflowTemplateDto) {
    return this.svc.createTemplate(dto)
  }

  @Get()
  findAll(@Query('practiceArea') practiceArea?: string) {
    return this.svc.findAllTemplates(practiceArea)
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.svc.findOneTemplate(id)
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() dto: UpdateWorkflowTemplateDto) {
    return this.svc.updateTemplate(id, dto)
  }

  @Delete(':id')
  @HttpCode(HttpStatus.NO_CONTENT)
  remove(@Param('id') id: string) {
    return this.svc.removeTemplate(id)
  }
}

// ── Instance endpoints ─────────────────────────────────────────────────────────

@Controller('workflows')
export class WorkflowsController {
  constructor(private readonly svc: WorkflowsService) {}

  // Instantiate a template into a matter
  @Post('instantiate')
  instantiate(@Body() dto: InstantiateWorkflowDto) {
    return this.svc.instantiate(dto)
  }

  // All workflows for a matter
  @Get('matter/:matterId')
  findByMatter(@Param('matterId') matterId: string) {
    return this.svc.findByMatter(matterId)
  }

  // Single workflow
  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.svc.findOneWorkflow(id)
  }

  // Update a step status
  @Patch(':id/steps/:stepId')
  updateStep(
    @Param('id') id: string,
    @Param('stepId') stepId: string,
    @Body() dto: UpdateStepDto,
  ) {
    return this.svc.updateStep(id, stepId, dto)
  }

  // Dashboard: overdue steps across all active workflows
  @Get('dashboard/overdue')
  getOverdue() {
    return this.svc.getOverdueSteps()
  }
}
