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
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
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TaskTrackingSystem.Database;
using TaskTrackingSystem.Database.AppDbContextModels;
using TaskTrackingSystem.Shared;
using TaskTrackingSystem.Shared.Enums;
using TaskTrackingSystem.Shared.Models.Task;
using TaskTrackingSystem.WebApi.Infrastructure;

namespace TaskTrackingSystem.WebApi.Features.Task
{
    public class TaskService
    {
        private readonly AppDbContext _db;
        private readonly TaskTrackingSystem.WebApi.Features.Notification.FirebaseNotificationService _notificationService;
        private readonly AuditLogService _auditLog;

        public TaskService(
            AppDbContext db,
            TaskTrackingSystem.WebApi.Features.Notification.FirebaseNotificationService notificationService,
            AuditLogService auditLog)
        {
            _db = db;
            _notificationService = notificationService;
            _auditLog = auditLog;
        }

        private static DateTime? GetCompletedAt(TaskTrackingSystem.Database.AppDbContextModels.Task task)
        {
            return task.StatusId == AppTaskStatus.Done
                ? task.UpdatedAt ?? task.CreatedAt
                : null;
        }

        private static DateTime ToUtcDate(DateTime value)
        {
            return value.Kind == DateTimeKind.Utc
                ? value
                : DateTime.SpecifyKind(value.Date, DateTimeKind.Utc);
        }

        public async Task<IEnumerable<TaskDto>> GetAllTasksAsync(long roleId, long currentUserId)
        {
            var query = await BuildAccessibleTaskQueryAsync(roleId, currentUserId);
            return await query
                .OrderBy(t => t.DueDate)
                .ThenByDescending(t => t.CreatedAt ?? DateTime.UtcNow)
                .Select(t => new TaskDto
                {
                    Id = t.Id,
                    Title = t.Title,
                    Description = t.Description,
                    ProjectId = t.ProjectId,
                    StatusId = t.StatusId,
                    PriorityId = t.PriorityId,
                    AssignedTo = t.AssignedTo,
                    AssignedBy = t.AssignedBy,
                    DueDate = t.DueDate,
                    CreatedAt = t.CreatedAt ?? DateTime.UtcNow,
                    IsArchived = t.IsArchived,
                    CompletedAt = GetCompletedAt(t)
                })
                .ToListAsync();
        }

        public async Task<PagedResult<TaskDto>> GetPagedTasksAsync(
            long roleId,
            long currentUserId,
            string? search,
            long? projectId,
            AppTaskStatus? statusId,
            TaskPriority? priorityId,
            bool assignedOnly,
            int page,
            int pageSize)
        {
            var query = await BuildAccessibleTaskQueryAsync(roleId, currentUserId);

            if (assignedOnly)
            {
                query = query.Where(t => t.AssignedTo == currentUserId);
            }

            if (!string.IsNullOrWhiteSpace(search))
            {
                var searchTerm = search.Trim().ToLower();
                query = query.Where(t =>
                    (t.Title != null && t.Title.ToLower().Contains(searchTerm)) ||
                    (t.Description != null && t.Description.ToLower().Contains(searchTerm)));
            }

            if (projectId.HasValue && projectId.Value > 0)
            {
                query = query.Where(t => t.ProjectId == projectId.Value);
            }

            if (statusId.HasValue)
            {
                query = query.Where(t => t.StatusId == statusId.Value);
            }

            if (priorityId.HasValue)
            {
                query = query.Where(t => t.PriorityId == priorityId.Value);
            }

            return await query
                .OrderBy(t => t.DueDate)
                .ThenByDescending(t => t.CreatedAt ?? DateTime.UtcNow)
                .Select(t => new TaskDto
                {
                    Id = t.Id,
                    Title = t.Title,
                    Description = t.Description,
                    ProjectId = t.ProjectId,
                    StatusId = t.StatusId,
                    PriorityId = t.PriorityId,
                    AssignedTo = t.AssignedTo,
                    AssignedBy = t.AssignedBy,
                    DueDate = t.DueDate,
                    CreatedAt = t.CreatedAt ?? DateTime.UtcNow,
                    IsArchived = t.IsArchived,
                    CompletedAt = GetCompletedAt(t)
                })
                .ToPagedResultAsync(page, pageSize);
        }

        public async Task<IEnumerable<TaskDto>> GetArchivedTasksAsync(long roleId, long currentUserId)
        {
            var query = await BuildAccessibleTaskQueryAsync(roleId, currentUserId, includeArchived: true);
            return await query
                .Where(t => t.IsArchived)
                .OrderByDescending(t => t.UpdatedAt ?? t.CreatedAt ?? DateTime.UtcNow)
                .Select(t => new TaskDto
                {
                    Id = t.Id,
                    Title = t.Title,
                    Description = t.Description,
                    ProjectId = t.ProjectId,
                    StatusId = t.StatusId,
                    PriorityId = t.PriorityId,
                    AssignedTo = t.AssignedTo,
                    AssignedBy = t.AssignedBy,
                    DueDate = t.DueDate,
                    CreatedAt = t.CreatedAt ?? DateTime.UtcNow,
                    IsArchived = t.IsArchived,
                    CompletedAt = GetCompletedAt(t)
                })
                .ToListAsync();
        }

        public async Task<TaskDto?> GetTaskByIdAsync(long id, long roleId, long currentUserId)
        {
            var query = await BuildAccessibleTaskQueryAsync(roleId, currentUserId);
            var task = await query.FirstOrDefaultAsync(t => t.Id == id);

            if (task == null)
            {
                return null;
            }

            return new TaskDto
            {
                Id = task.Id,
                Title = task.Title,
                Description = task.Description,
                ProjectId = task.ProjectId,
                StatusId = task.StatusId,
                PriorityId = task.PriorityId,
                AssignedTo = task.AssignedTo,
                AssignedBy = task.AssignedBy,
                DueDate = task.DueDate,
                CreatedAt = task.CreatedAt ?? DateTime.UtcNow,
                IsArchived = task.IsArchived,
                CompletedAt = GetCompletedAt(task)
            };
        }

        public async Task<Result<TaskDto>> CreateTaskAsync(CreateTaskDto dto, long roleId, long currentUserId)
        {
            if (string.IsNullOrWhiteSpace(dto.Title))
            {
                return Result<TaskDto>.Failure(ResultMessages.TaskTitleRequired, 400);
            }

            if (dto.ProjectId == 0)
            {
                return Result<TaskDto>.Failure(ResultMessages.SelectProjectRequired, 400);
            }

            var projectExists = await _db.Projects.AnyAsync(p => p.Id == dto.ProjectId && p.IsDeleted != true);
            if (!projectExists)
            {
                return Result<TaskDto>.Failure(ResultMessages.ProjectNotFound(dto.ProjectId), 404);
            }

            if (!await CanAccessProjectAsync(dto.ProjectId, roleId, currentUserId))
            {
                return Result<TaskDto>.Failure("You do not have access to this project.", 403);
            }

            if (dto.AssignedTo.HasValue && !await IsProjectMemberAsync(dto.ProjectId, dto.AssignedTo.Value))
            {
                return Result<TaskDto>.Failure("Task assignee must belong to the selected project.", 400);
            }

            var task = new TaskTrackingSystem.Database.AppDbContextModels.Task
            {
                Title = dto.Title,
                Description = dto.Description,
                ProjectId = dto.ProjectId,
                StatusId = dto.StatusId == 0 ? AppTaskStatus.Todo : dto.StatusId,
                PriorityId = dto.PriorityId == 0 ? TaskPriority.Medium : dto.PriorityId,
                AssignedTo = dto.AssignedTo,
                AssignedBy = dto.AssignedBy,
                DueDate = ToUtcDate(dto.DueDate),
                IsDeleted = false,
                IsArchived = false,
                CreatedAt = DateTime.UtcNow,
                CreatedBy = currentUserId
            };

            _db.Tasks.Add(task);
            await _db.SaveChangesAsync();
            await _auditLog.LogAsync("Create", "Task", $"Created task '{task.Title}'");

            if (task.AssignedTo.HasValue)
            {
                await _notificationService.NotifyTaskAssignedAsync(task, currentUserId);
            }

            var resultDto = new TaskDto
            {
                Id = task.Id,
                Title = task.Title,
                Description = task.Description,
                ProjectId = task.ProjectId,
                StatusId = task.StatusId,
                PriorityId = task.PriorityId,
                AssignedTo = task.AssignedTo,
                AssignedBy = task.AssignedBy,
                DueDate = task.DueDate,
                CreatedAt = task.CreatedAt ?? DateTime.UtcNow,
                CompletedAt = null,
                IsArchived = task.IsArchived
            };

            return Result<TaskDto>.Success(resultDto, 201);
        }

        public async Task<Result> UpdateTaskAsync(long id, UpdateTaskDto dto, long? currentUserId = null)
        {
            if (string.IsNullOrWhiteSpace(dto.Title))
            {
                return Result.Failure(ResultMessages.TaskTitleRequired, 400);
            }

            var task = await _db.Tasks.FirstOrDefaultAsync(t => t.Id == id && t.IsDeleted != true && !t.IsArchived);
            if (task == null)
            {
                return Result.Failure(ResultMessages.TaskNotFound(id), 404);
            }

            var previousStatusId = task.StatusId;
            var previousAssignedTo = task.AssignedTo;

            if (dto.AssignedTo.HasValue && !await IsProjectMemberAsync(task.ProjectId, dto.AssignedTo.Value))
            {
                return Result.Failure("Task assignee must belong to the selected project.", 400);
            }

            task.Title = dto.Title;
            task.Description = dto.Description;
            task.StatusId = dto.StatusId;
            task.PriorityId = dto.PriorityId;
            task.AssignedTo = dto.AssignedTo;
            task.AssignedBy = dto.AssignedBy;
            task.DueDate = ToUtcDate(dto.DueDate);
            task.UpdatedAt = DateTime.UtcNow;
            task.UpdatedBy = currentUserId;

            _db.Tasks.Update(task);
            await _db.SaveChangesAsync();
            await _auditLog.LogAsync("Update", "Task", $"Updated task '{task.Title}'");

            if (previousAssignedTo != task.AssignedTo && task.AssignedTo.HasValue && currentUserId.HasValue)
            {
                await _notificationService.NotifyTaskAssignedAsync(task, currentUserId.Value);
            }

            if (previousStatusId != dto.StatusId && currentUserId.HasValue)
            {
                await _notificationService.NotifyTaskStatusChangedAsync(task, currentUserId.Value, previousStatusId, dto.StatusId);
            }

            return Result.Success(200);
        }

        public async Task<Result> SoftDeleteTaskAsync(long id, long currentUserId)
        {
            var task = await _db.Tasks.FirstOrDefaultAsync(t => t.Id == id && t.IsDeleted != true && !t.IsArchived);
            if (task == null)
            {
                return Result.Failure(ResultMessages.TaskNotFound(id), 404);
            }

            task.IsDeleted = true;
            task.UpdatedAt = DateTime.UtcNow;
            task.UpdatedBy = currentUserId;
            _db.Tasks.Update(task);
            await _db.SaveChangesAsync();
            await _auditLog.LogAsync("Delete", "Task", $"Deleted task '{task.Title}'");
            return Result.Success(200);
        }

        public async Task<Result<IEnumerable<TaskDto>>> GetTasksByUserIdAsync(long userId, long roleId, long currentUserId)
        {
            var userExists = await _db.Users.AnyAsync(u => u.Id == userId && !u.IsDeleted);
            if (!userExists)
            {
                return Result<IEnumerable<TaskDto>>.Failure(ResultMessages.UserNotFound(userId), 404);
            }

            var query = await BuildAccessibleTaskQueryAsync(roleId, currentUserId);
            var tasks = await query
                .Where(t => t.AssignedTo == userId)
                .Select(t => new TaskDto
                {
                    Id = t.Id,
                    Title = t.Title,
                    Description = t.Description,
                    ProjectId = t.ProjectId,
                    StatusId = t.StatusId,
                    PriorityId = t.PriorityId,
                    AssignedTo = t.AssignedTo,
                    AssignedBy = t.AssignedBy,
                    DueDate = t.DueDate,
                    CreatedAt = t.CreatedAt ?? DateTime.UtcNow,
                    IsArchived = t.IsArchived,
                    CompletedAt = GetCompletedAt(t)
                })
                .ToListAsync();

            return Result<IEnumerable<TaskDto>>.Success(tasks);
        }

        public async Task<Result> UpdateTaskStatusAsync(long id, AppTaskStatus statusId, long roleId, long currentUserId)
        {
            var task = await _db.Tasks.FirstOrDefaultAsync(t => t.Id == id && t.IsDeleted != true && !t.IsArchived);
            if (task == null)
            {
                return Result.Failure(ResultMessages.TaskNotFound(id), 404);
            }

            var previousStatusId = task.StatusId;

            task.StatusId = statusId;
            task.UpdatedAt = DateTime.UtcNow;
            task.UpdatedBy = currentUserId;

            _db.Tasks.Update(task);
            await _db.SaveChangesAsync();

            if (previousStatusId != statusId)
            {
                await _notificationService.NotifyTaskStatusChangedAsync(task, currentUserId, previousStatusId, statusId);
            }

            return Result.Success(200);
        }

        public async Task<Result<int>> ArchiveDoneTasksAsync(long? projectId, long roleId, long currentUserId)
        {
            if (projectId.HasValue && projectId.Value > 0)
            {
                var projectExists = await _db.Projects.AnyAsync(p => p.Id == projectId.Value && p.IsDeleted != true);
                if (!projectExists)
                {
                    return Result<int>.Failure(ResultMessages.ProjectNotFound(projectId.Value), 404);
                }

                if (!await CanAccessProjectAsync(projectId.Value, roleId, currentUserId))
                {
                    return Result<int>.Failure("You do not have access to this project.", 403);
                }
            }

            var query = await BuildAccessibleTaskQueryAsync(roleId, currentUserId);
            var tasksToArchive = await query
                .Where(t => t.StatusId == AppTaskStatus.Done)
                .ToListAsync();

            if (projectId.HasValue && projectId.Value > 0)
            {
                tasksToArchive = tasksToArchive.Where(t => t.ProjectId == projectId.Value).ToList();
            }

            foreach (var task in tasksToArchive)
            {
                task.IsArchived = true;
                task.UpdatedAt = DateTime.UtcNow;
                task.UpdatedBy = currentUserId;
            }

            if (tasksToArchive.Count > 0)
            {
                _db.Tasks.UpdateRange(tasksToArchive);
                await _db.SaveChangesAsync();
            }

            return Result<int>.Success(tasksToArchive.Count);
        }

        private async Task<IQueryable<TaskTrackingSystem.Database.AppDbContextModels.Task>> BuildAccessibleTaskQueryAsync(long roleId, long currentUserId, bool includeArchived = false)
        {
            var query = _db.Tasks.Where(t => t.IsDeleted != true && (includeArchived || !t.IsArchived));

            var isAdmin = await DataScopeAuthorization.IsAdminScopeAsync(_db, roleId);
            if (isAdmin)
            {
                return query;
            }

            var isManager = await DataScopeAuthorization.IsManagerScopeAsync(_db, roleId);
            if (isManager)
            {
                return query.Where(t =>
                    t.AssignedTo == currentUserId ||
                    t.CreatedBy == currentUserId ||
                    t.Project.ProjectMembers.Any(pm => pm.UserId == currentUserId));
            }

            return query.Where(t =>
                t.AssignedTo == currentUserId ||
                t.CreatedBy == currentUserId);
        }

        private async Task<bool> CanAccessProjectAsync(long projectId, long roleId, long currentUserId)
        {
            var isAdmin = await DataScopeAuthorization.IsAdminScopeAsync(_db, roleId);
            if (isAdmin)
            {
                return await _db.Projects.AnyAsync(p => p.Id == projectId && p.IsDeleted != true);
            }

            return await _db.Projects.AnyAsync(p =>
                p.Id == projectId &&
                p.IsDeleted != true &&
                (p.CreatedById == currentUserId || p.ProjectMembers.Any(pm => pm.UserId == currentUserId)));
        }

        private async Task<bool> IsProjectMemberAsync(long projectId, long userId)
        {
            return await _db.ProjectMembers.AnyAsync(pm => pm.ProjectId == projectId && pm.UserId == userId);
        }
    }
}