File size: 21,826 Bytes
fd07338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c85b71
fd07338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4870a77
 
 
 
fd07338
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Patch,
  Body,
  Param,
  Query,
  Req,
  UseGuards,
  ParseIntPipe,
  HttpCode,
  HttpStatus,
  UseInterceptors,
  UploadedFile,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import {
  ApiTags,
  ApiOperation,
  ApiParam,
  ApiBody,
  ApiResponse,
  ApiBearerAuth,
  ApiConsumes,
} from '@nestjs/swagger';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../../auth/guards/roles.guard';
import { Roles } from '../../auth/roles.decorator';
import { RoleName } from '../../auth/entities/role.entity';
import { MaterialsService } from '../services';
import {
  CreateMaterialDto,
  UpdateMaterialDto,
  QueryMaterialsDto,
  ToggleVisibilityDto,
  UploadVideoMaterialDto,
  UploadDocumentMaterialDto,
  BulkCreateMaterialDto,
} from '../dto';
import { MaterialType } from '../enums';

@ApiTags('πŸ“š Course Materials')
@ApiBearerAuth('JWT-auth')
@Controller('api/courses/:courseId/materials')
@UseGuards(JwtAuthGuard, RolesGuard)
export class MaterialsController {
  constructor(private readonly materialsService: MaterialsService) {}

  @Get()
  @ApiOperation({
    summary: 'List course materials',
    description: `
## List Course Materials

Returns paginated list of materials for a course.

### Access Control
- **Authentication Required**: βœ… Yes (Bearer Token)
- **Roles**: ALL (filtered by role)

### Role-Based Visibility
- **Students**: See only published materials
- **Instructors/TAs**: See all materials (including drafts)
- **Admins**: See all materials

### Query Parameters
- \`materialType\`: Filter by type (lecture, slide, video, etc.)
- \`search\`: Search in title and description
- \`isPublished\`: Filter by visibility (instructors/admins only)
    `,
  })
  @ApiParam({ name: 'courseId', description: 'Course ID', type: Number, example: 1 })
  @ApiResponse({ status: 200, description: 'Paginated list of materials' })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  async findAll(
    @Param('courseId', ParseIntPipe) courseId: number,
    @Query() query: QueryMaterialsDto,
    @Req() req: any,
  ) {
    const userId = req.user.userId || req.user.id;
    const roles = this.extractRoles(req.user);
    return this.materialsService.findAll(courseId, query, userId, roles);
  }

  @Post()
  @Roles(RoleName.INSTRUCTOR, RoleName.TA, RoleName.ADMIN, RoleName.IT_ADMIN)
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({
    summary: 'Create course material',
    description: `
## Create Course Material

Adds a new material to the course.

### Access Control
- **Authentication Required**: βœ… Yes (Bearer Token)
- **Roles**: INSTRUCTOR, TA, ADMIN

### Material Types
- \`lecture\`: Lecture content
- \`slide\`: Presentation slides
- \`video\`: Video content (can use YouTube integration)
- \`reading\`: Reading material
- \`link\`: External link
- \`document\`: Generic document

### File Upload
For file-based materials, upload the file first using the Files API and pass the \`fileId\`.
    `,
  })
  @ApiParam({ name: 'courseId', description: 'Course ID', type: Number, example: 1 })
  @ApiBody({ type: CreateMaterialDto })
  @ApiResponse({ status: 201, description: 'Material created successfully' })
  @ApiResponse({ status: 400, description: 'Invalid input data' })
  @ApiResponse({ status: 403, description: 'Forbidden' })
  async create(
    @Param('courseId', ParseIntPipe) courseId: number,
    @Body() dto: CreateMaterialDto,
    @Req() req: any,
  ) {
    const userId = req.user.userId || req.user.id;
    const roles = this.extractRoles(req.user);
    return this.materialsService.create(courseId, dto, userId, roles);
  }

  @Post('bulk')
  @Roles(RoleName.INSTRUCTOR, RoleName.TA, RoleName.ADMIN, RoleName.IT_ADMIN)
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({
    summary: 'Bulk create materials',
    description: `
## Bulk Create Course Materials

Creates multiple materials in a single request. Maximum 50 materials per request.

### Access Control
- **Authentication Required**: βœ… Yes (Bearer Token)
- **Roles**: INSTRUCTOR, TA, ADMIN

### Use Cases
- Setting up course content at the beginning of a semester
- Importing materials from another course
- Uploading multiple lecture notes at once

### Request Body
\`\`\`json
{
  "materials": [
    { "title": "Lecture 1", "materialType": "lecture", "weekNumber": 1 },
    { "title": "Lecture 2", "materialType": "lecture", "weekNumber": 2 }
  ]
}
\`\`\`
    `,
  })
  @ApiParam({ name: 'courseId', description: 'Course ID', type: Number, example: 1 })
  @ApiBody({ type: BulkCreateMaterialDto })
  @ApiResponse({ status: 201, description: 'Materials created successfully' })
  @ApiResponse({ status: 400, description: 'Invalid input data' })
  @ApiResponse({ status: 403, description: 'Forbidden' })
  async bulkCreate(
    @Param('courseId', ParseIntPipe) courseId: number,
    @Body() dto: BulkCreateMaterialDto,
    @Req() req: any,
  ) {
    const userId = req.user.userId || req.user.id;
    const roles = this.extractRoles(req.user);
    return this.materialsService.bulkCreate(courseId, dto.materials, userId, roles);
  }

  @Post('video')
  @Roles(RoleName.INSTRUCTOR, RoleName.TA, RoleName.ADMIN, RoleName.IT_ADMIN)
  @HttpCode(HttpStatus.CREATED)
  @UseInterceptors(FileInterceptor('video'))
  @ApiConsumes('multipart/form-data')
  @ApiOperation({
    summary: 'Upload video material to YouTube',
    description: `
## Upload Video Material via YouTube

Uploads a video file to YouTube (as unlisted) and creates a course material record.

### Access Control
- **Authentication Required**: βœ… Yes (Bearer Token)
- **Roles**: INSTRUCTOR, TA, ADMIN, IT_ADMIN
- **Authorization**: Must be assigned to the course (or be admin)

### Supported Video Formats
\`mp4\`, \`avi\`, \`mov\`, \`webm\`, \`mkv\`, \`flv\`, \`wmv\`

### Upload Flow
1. Backend validates user is authorized for this course
2. Video is uploaded to YouTube (unlisted privacy)
3. YouTube returns video ID and URL
4. Material record created with:
   - \`externalUrl\`: YouTube embed URL
   - \`youtubeVideoId\`: Original YouTube video ID (for future updates/deletes)
   - Other metadata (weekNumber, orderIndex, isPublished)

### Form Data Fields
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| video | file | βœ… | Video file to upload |
| title | string | βœ… | Video title (max 255 chars) |
| description | string | ❌ | Video description |
| tags | string[] | ❌ | Tags for the video |
| weekNumber | number | ❌ | Week to assign (1-52) |
| orderIndex | number | ❌ | Sort order (default: 0) |
| isPublished | boolean | ❌ | Publish immediately (default: false/draft) |

### Response
Returns material object with:
- \`externalUrl\`: YouTube embed URL for iframe
- \`youtubeVideoId\`: YouTube video ID
- \`youtubeUrl\`: Full YouTube watch URL
- \`embedUrl\`: Embed URL for iframe usage
    `,
  })
  @ApiParam({ name: 'courseId', description: 'Course ID', type: Number, example: 1 })
  @ApiBody({
    schema: {
      type: 'object',
      required: ['video', 'title'],
      properties: {
        video: {
          type: 'string',
          format: 'binary',
          description: 'Video file (mp4, avi, mov, webm, mkv)',
        },
        title: {
          type: 'string',
          example: 'Lecture 1: Introduction to Data Structures',
          maxLength: 255,
        },
        description: {
          type: 'string',
          example: 'This video covers the basics of data structures.',
        },
        tags: {
          type: 'array',
          items: { type: 'string' },
          example: ['lecture', 'data-structures', 'cs101'],
        },
        weekNumber: {
          type: 'integer',
          example: 1,
          minimum: 1,
          maximum: 52,
        },
        orderIndex: {
          type: 'integer',
          example: 0,
          default: 0,
        },
        isPublished: {
          type: 'boolean',
          example: false,
          default: false,
        },
      },
    },
  })
  @ApiResponse({ 
    status: 201, 
    description: 'Video uploaded to YouTube and material created',
    schema: {
      example: {
        materialId: 1,
        courseId: 1,
        title: 'Lecture 1: Introduction',
        materialType: 'video',
        externalUrl: 'https://www.youtube.com/embed/dQw4w9WgXcQ',
        youtubeVideoId: 'dQw4w9WgXcQ',
        weekNumber: 1,
        orderIndex: 0,
        isPublished: false,
        youtubeUrl: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
        embedUrl: 'https://www.youtube.com/embed/dQw4w9WgXcQ',
      },
    },
  })
  @ApiResponse({ status: 400, description: 'Invalid input data or YouTube upload failed' })
  @ApiResponse({ status: 403, description: 'Forbidden - not assigned to course' })
  async uploadVideo(
    @Param('courseId', ParseIntPipe) courseId: number,
    @UploadedFile() file: Express.Multer.File,
    @Body() dto: UploadVideoMaterialDto,
    @Req() req: any,
  ) {
    const userId = req.user.userId || req.user.id;
    const roles = this.extractRoles(req.user);
    return this.materialsService.uploadVideoMaterial(
      courseId,
      file,
      dto.title,
      dto.description || '',
      dto.tags || [],
      userId,
      roles,
      dto.weekNumber,
      dto.orderIndex,
      dto.isPublished,
    );
  }

  @Post('document')
  @Roles(RoleName.INSTRUCTOR, RoleName.TA, RoleName.ADMIN, RoleName.IT_ADMIN)
  @HttpCode(HttpStatus.CREATED)
  @UseInterceptors(FileInterceptor('document'))
  @ApiConsumes('multipart/form-data')
  @ApiOperation({
    summary: 'Upload document material to Google Drive',
    description: `
## Upload Document Material via Google Drive

Uploads a document file (PDF, PPT, Word, etc.) to Google Drive and creates a course material record.

### Access Control
- **Authentication Required**: βœ… Yes (Bearer Token)
- **Roles**: INSTRUCTOR, TA, ADMIN, IT_ADMIN
- **Authorization**: Must be assigned to the course (or be admin)

### Supported Document Formats
\`pdf\`, \`ppt\`, \`pptx\`, \`doc\`, \`docx\`, \`xls\`, \`xlsx\`, \`txt\`, \`md\`, \`zip\`

### Upload Flow
1. Backend validates user is authorized for this course
2. Course folder hierarchy is created/verified in Google Drive
3. Document is uploaded to the appropriate folder (Lectures or General)
4. Material record created with Drive metadata

### Form Data Fields
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| document | file | βœ… | Document file to upload |
| title | string | βœ… | Document title (max 255 chars) |
| description | string | ❌ | Document description |
| materialType | enum | ❌ | Type: lecture, slide, reading, document (default: document) |
| weekNumber | number | ❌ | Week to assign (1-52) |
| orderIndex | number | ❌ | Sort order (default: 0) |
| isPublished | boolean | ❌ | Publish immediately (default: false/draft) |

### Folder Placement
- \`lecture\` and \`slide\` types β†’ Course/Lectures/ folder
- \`reading\`, \`document\`, \`link\` β†’ Course/General/ folder

### Response
Returns material object with:
- \`driveId\`: Google Drive file ID
- \`driveViewUrl\`: URL to view in Google Drive
- \`driveDownloadUrl\`: Direct download URL
    `,
  })
  @ApiParam({ name: 'courseId', description: 'Course ID', type: Number, example: 1 })
  @ApiBody({
    schema: {
      type: 'object',
      required: ['document', 'title'],
      properties: {
        document: {
          type: 'string',
          format: 'binary',
          description: 'Document file (pdf, ppt, pptx, doc, docx, xls, xlsx)',
        },
        title: {
          type: 'string',
          example: 'Week 1 Lecture Notes: Introduction to Data Structures',
          maxLength: 255,
        },
        description: {
          type: 'string',
          example: 'Comprehensive lecture notes covering the basics.',
        },
        materialType: {
          type: 'string',
          enum: ['lecture', 'slide', 'reading', 'document', 'link'],
          example: 'lecture',
          default: 'document',
        },
        weekNumber: {
          type: 'integer',
          example: 1,
          minimum: 1,
          maximum: 52,
        },
        orderIndex: {
          type: 'integer',
          example: 0,
          default: 0,
        },
        isPublished: {
          type: 'boolean',
          example: false,
          default: false,
        },
      },
    },
  })
  @ApiResponse({ 
    status: 201, 
    description: 'Document uploaded to Google Drive and material created',
    schema: {
      example: {
        materialId: 1,
        courseId: 1,
        title: 'Week 1 Lecture Notes',
        materialType: 'lecture',
        externalUrl: 'https://drive.google.com/file/d/abc123/view',
        driveId: 'abc123',
        driveViewUrl: 'https://drive.google.com/file/d/abc123/view',
        driveDownloadUrl: 'https://drive.google.com/uc?id=abc123&export=download',
        weekNumber: 1,
        orderIndex: 0,
        isPublished: false,
        fileName: 'Week01_Week_1_Lecture_Notes_v1.pdf',
      },
    },
  })
  @ApiResponse({ status: 400, description: 'Invalid input data or Drive upload failed' })
  @ApiResponse({ status: 403, description: 'Forbidden - not assigned to course' })
  async uploadDocument(
    @Param('courseId', ParseIntPipe) courseId: number,
    @UploadedFile() file: Express.Multer.File,
    @Body() dto: UploadDocumentMaterialDto,
    @Req() req: any,
  ) {
    const userId = req.user.userId || req.user.id;
    const roles = this.extractRoles(req.user);
    return this.materialsService.uploadDocumentMaterial(
      courseId,
      file,
      dto.title,
      dto.description || '',
      dto.materialType || MaterialType.DOCUMENT,
      userId,
      roles,
      dto.weekNumber,
      dto.orderIndex,
      dto.isPublished,
    );
  }

  @Get(':id')
  @ApiOperation({
    summary: 'Get material by ID',
    description: `
## Get Material Details

Returns detailed information about a specific material.

### Access Control
- **Authentication Required**: βœ… Yes (Bearer Token)
- **Roles**: ALL (students can only see published materials)
    `,
  })
  @ApiParam({ name: 'courseId', description: 'Course ID', type: Number, example: 1 })
  @ApiParam({ name: 'id', description: 'Material ID', type: Number, example: 1 })
  @ApiResponse({ status: 200, description: 'Material details' })
  @ApiResponse({ status: 404, description: 'Material not found' })
  async findById(
    @Param('courseId', ParseIntPipe) courseId: number,
    @Param('id', ParseIntPipe) id: number,
    @Req() req: any,
  ) {
    const userId = req.user.userId || req.user.id;
    const roles = this.extractRoles(req.user);
    return this.materialsService.findById(id, userId, roles);
  }

  @Put(':id')
  @Roles(RoleName.INSTRUCTOR, RoleName.TA, RoleName.ADMIN, RoleName.IT_ADMIN)
  @ApiOperation({
    summary: 'Update material',
    description: `
## Update Material

Updates an existing material's metadata.

### Access Control
- **Authentication Required**: βœ… Yes (Bearer Token)
- **Roles**: INSTRUCTOR, TA, ADMIN
    `,
  })
  @ApiParam({ name: 'courseId', description: 'Course ID', type: Number, example: 1 })
  @ApiParam({ name: 'id', description: 'Material ID', type: Number, example: 1 })
  @ApiBody({ type: UpdateMaterialDto })
  @ApiResponse({ status: 200, description: 'Material updated successfully' })
  @ApiResponse({ status: 404, description: 'Material not found' })
  @ApiResponse({ status: 403, description: 'Forbidden' })
  async update(
    @Param('courseId', ParseIntPipe) courseId: number,
    @Param('id', ParseIntPipe) id: number,
    @Body() dto: UpdateMaterialDto,
    @Req() req: any,
  ) {
    const userId = req.user.userId || req.user.id;
    const roles = this.extractRoles(req.user);
    return this.materialsService.update(id, dto, userId, roles);
  }

  @Delete(':id')
  @Roles(RoleName.INSTRUCTOR, RoleName.TA, RoleName.ADMIN, RoleName.IT_ADMIN)
  @HttpCode(HttpStatus.OK)
  @ApiOperation({
    summary: 'Delete material',
    description: `
## Delete Material

Removes a material from the course.

### Access Control
- **Authentication Required**: βœ… Yes (Bearer Token)
- **Roles**: INSTRUCTOR, ADMIN only (TAs cannot delete)
    `,
  })
  @ApiParam({ name: 'courseId', description: 'Course ID', type: Number, example: 1 })
  @ApiParam({ name: 'id', description: 'Material ID', type: Number, example: 1 })
  @ApiResponse({ status: 200, description: 'Material deleted successfully' })
  @ApiResponse({ status: 404, description: 'Material not found' })
  @ApiResponse({ status: 403, description: 'Forbidden' })
  async delete(
    @Param('courseId', ParseIntPipe) courseId: number,
    @Param('id', ParseIntPipe) id: number,
    @Req() req: any,
  ) {
    const userId = req.user.userId || req.user.id;
    const roles = this.extractRoles(req.user);
    return this.materialsService.delete(id, userId, roles);
  }

  @Patch(':id/visibility')
  @Roles(RoleName.INSTRUCTOR, RoleName.TA, RoleName.ADMIN, RoleName.IT_ADMIN)
  @ApiOperation({
    summary: 'Toggle material visibility',
    description: `
## Toggle Material Visibility

Show or hide a material from students.

### Access Control
- **Authentication Required**: βœ… Yes (Bearer Token)
- **Roles**: INSTRUCTOR, TA, ADMIN

### Visibility States
- \`isPublished: true\`: Visible to students
- \`isPublished: false\`: Hidden from students (draft mode)
    `,
  })
  @ApiParam({ name: 'courseId', description: 'Course ID', type: Number, example: 1 })
  @ApiParam({ name: 'id', description: 'Material ID', type: Number, example: 1 })
  @ApiBody({ type: ToggleVisibilityDto })
  @ApiResponse({ status: 200, description: 'Visibility updated' })
  @ApiResponse({ status: 404, description: 'Material not found' })
  async toggleVisibility(
    @Param('courseId', ParseIntPipe) courseId: number,
    @Param('id', ParseIntPipe) id: number,
    @Body() dto: ToggleVisibilityDto,
    @Req() req: any,
  ) {
    const userId = req.user.userId || req.user.id;
    const roles = this.extractRoles(req.user);
    return this.materialsService.toggleVisibility(id, dto, userId, roles);
  }

  @Get(':id/download')
  @ApiOperation({
    summary: 'Download material',
    description: `
## Download Material File

Get download information for a material's associated file.

### Access Control
- **Authentication Required**: βœ… Yes (Bearer Token)
- **Roles**: ALL (students can only download published materials)

### Response
Returns file information including download URL.
    `,
  })
  @ApiParam({ name: 'courseId', description: 'Course ID', type: Number, example: 1 })
  @ApiParam({ name: 'id', description: 'Material ID', type: Number, example: 1 })
  @ApiResponse({ status: 200, description: 'Download information' })
  @ApiResponse({ status: 400, description: 'Material has no downloadable file' })
  @ApiResponse({ status: 404, description: 'Material not found' })
  async download(
    @Param('courseId', ParseIntPipe) courseId: number,
    @Param('id', ParseIntPipe) id: number,
    @Req() req: any,
  ) {
    const userId = req.user.userId || req.user.id;
    const roles = this.extractRoles(req.user);
    return this.materialsService.download(id, userId, roles);
  }

  @Post(':id/view')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({
    summary: 'Track material view',
    description: `
## Track Material View

Records that a user viewed a material and increments the view counter.

### Access Control
- **Authentication Required**: βœ… Yes (Bearer Token)
- **Roles**: ALL

### Use Cases
- Analytics tracking for course engagement
- Identifying popular materials
- Measuring student participation

### Response
Returns updated view count for the material.
    `,
  })
  @ApiParam({ name: 'courseId', description: 'Course ID', type: Number, example: 1 })
  @ApiParam({ name: 'id', description: 'Material ID', type: Number, example: 1 })
  @ApiResponse({ status: 200, description: 'View tracked successfully' })
  @ApiResponse({ status: 404, description: 'Material not found' })
  async trackView(
    @Param('courseId', ParseIntPipe) courseId: number,
    @Param('id', ParseIntPipe) id: number,
    @Req() req: any,
  ) {
    const userId = req.user.userId || req.user.id;
    const roles = this.extractRoles(req.user);
    return this.materialsService.trackView(id, userId, roles);
  }

  @Get(':id/embed')
  @ApiOperation({
    summary: 'Get embed URL',
    description: `
## Get YouTube Embed URL

For video materials, returns the YouTube embed URL and iframe HTML.

### Access Control
- **Authentication Required**: βœ… Yes (Bearer Token)
- **Roles**: ALL

### Response
- \`videoId\`: YouTube video ID
- \`embedUrl\`: URL for iframe src
- \`iframeHtml\`: Ready-to-use iframe HTML
    `,
  })
  @ApiParam({ name: 'courseId', description: 'Course ID', type: Number, example: 1 })
  @ApiParam({ name: 'id', description: 'Material ID', type: Number, example: 1 })
  @ApiResponse({ status: 200, description: 'Embed information' })
  @ApiResponse({ status: 400, description: 'Material is not a video' })
  @ApiResponse({ status: 404, description: 'Material not found' })
  async getEmbedUrl(
    @Param('courseId', ParseIntPipe) courseId: number,
    @Param('id', ParseIntPipe) id: number,
    @Req() req: any,
  ) {
    const userId = req.user.userId || req.user.id;
    const roles = this.extractRoles(req.user);
    return this.materialsService.getEmbedUrl(id, userId, roles);
  }

  private extractRoles(user: any): string[] {
    if (Array.isArray(user.roles)) {
      return user.roles.map((r: any) => {
        const roleStr = typeof r === 'string' ? r : r.name || r.roleName;
        return roleStr ? String(roleStr).toLowerCase() : '';
      }).filter(Boolean);
    }
    return [];
  }
}