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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Todo service layer - Business logic for todo operations

Implements CRUD operations for todos using PostgreSQL database.
This module provides the business logic layer, keeping route handlers thin.

Storage:
- PostgreSQL database with SQLAlchemy async ORM
- Database sessions provided via dependency injection
- Transactions managed with commit/rollback
- User-scoped todos (filtered by user_id)
"""

from typing import List, Dict, Optional, Union
from datetime import datetime
from fastapi import HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select

from models.database_todo import Todo, PriorityEnum, RecurrenceEnum


async def create_todo(
    description: str,
    user_id: int,
    priority: Optional[PriorityEnum] = None,
    tags: Optional[List[str]] = None,
    due_date: Optional[Union[str, datetime]] = None,
    recurrence_type: Optional[RecurrenceEnum] = None,
    reminder_time: Optional[Union[int, str]] = None,
    db: AsyncSession = None
) -> Dict:
    """
    Create a new todo in the database for authenticated user

    Args:
        description: Task description (1-500 characters)
        user_id: ID of the authenticated user (owner)
        priority: Task priority level (HIGH, MEDIUM, LOW)
        tags: Array of tags for categorization
        due_date: Deadline for the task (ISO 8601 format string)
        recurrence_type: Recurrence pattern (NONE, DAILY, WEEKLY, MONTHLY)
        reminder_time: Minutes before due time for notification
        db: Async database session

    Returns:
        Dict containing the created todo with all fields

    Business Rules:
        - ID auto-generated by database
        - completed defaults to False
        - user_id set to authenticated user's ID
        - created_at and updated_at set by database defaults
        - Transaction committed on success, rolled back on error

    Raises:
        HTTPException: 500 if database error occurs
    """
    try:
        # Prepare the todo with all fields
        todo_data = {
            "description": description,
            "user_id": user_id,
            "completed": False
        }

        if priority is not None:
            todo_data["priority"] = priority
        if tags is not None:
            todo_data["tags"] = tags
        if due_date is not None:
            # Handle both string and datetime types for due_date
            if isinstance(due_date, str):
                # Parse the ISO 8601 date string with proper timezone handling
                try:
                    # Handle different ISO 8601 formats that may come from the frontend
                    date_str = due_date.strip()

                    # If the date string is empty, set to None
                    if not date_str:
                        todo_data["due_date"] = None
                    else:
                        # Handle 'Z' suffix (UTC timezone) by replacing with '+00:00'
                        if date_str.endswith('Z'):
                            date_str = date_str[:-1] + '+00:00'

                        # Handle the 'T' separator for datetime format
                        if 'T' in date_str:
                            # Replace 'T' with ' ' for fromisoformat compatibility
                            date_str = date_str.replace('T', ' ')

                        # Parse the datetime string
                        parsed_date = datetime.fromisoformat(date_str)
                        todo_data["due_date"] = parsed_date
                except ValueError as e:
                    raise HTTPException(status_code=400, detail=f"Invalid due_date format. Use ISO 8601 format (e.g., 2023-12-31T18:00:00 or 2023-12-31 18:00:00). Error: {str(e)}")
            elif isinstance(due_date, datetime):
                # If it's already a datetime object (from Pydantic model), use it directly
                todo_data["due_date"] = due_date
            else:
                # If it's neither a string nor datetime, set to None
                todo_data["due_date"] = None
        if recurrence_type is not None:
            todo_data["recurrence_type"] = recurrence_type
        if reminder_time is not None:
            # Ensure reminder_time is converted to integer
            if isinstance(reminder_time, str):
                if reminder_time == "":
                    todo_data["reminder_time"] = 10  # Default value
                else:
                    try:
                        todo_data["reminder_time"] = int(reminder_time)
                    except ValueError:
                        raise HTTPException(status_code=400, detail="Invalid reminder_time format. Must be a number.")
            else:
                # It's already an int
                todo_data["reminder_time"] = int(reminder_time)

        todo = Todo(**todo_data)
        db.add(todo)
        await db.commit()
        await db.refresh(todo)

        return {
            "id": todo.id,
            "description": todo.description,
            "completed": todo.completed,
            "priority": todo.priority,
            "tags": todo.tags,
            "due_date": todo.due_date,
            "recurrence_type": todo.recurrence_type,
            "reminder_time": todo.reminder_time,
            "user_id": todo.user_id,
            "created_at": todo.created_at,
            "updated_at": todo.updated_at
        }
    except HTTPException:
        # Re-raise HTTP exceptions (like the invalid date format error)
        raise
    except Exception as e:
        await db.rollback()
        raise HTTPException(status_code=500, detail=f"Failed to create todo: {str(e)}")


async def list_todos(
    user_id: int,
    db: AsyncSession,
    search: Optional[str] = None,
    status: Optional[str] = None,
    priority: Optional[str] = None,
    tags: Optional[str] = None,
    recurrence: Optional[str] = None,
    sort_by: Optional[str] = None,
    order: Optional[str] = None,
    limit: Optional[int] = None,
    offset: Optional[int] = None
) -> List[Dict]:
    """
    Return all todos for authenticated user from the database with optional filtering and sorting

    Args:
        user_id: ID of the authenticated user
        db: Async database session
        search: Keyword to search in description
        status: Filter by completion status ('completed' or 'incomplete')
        priority: Filter by priority level ('HIGH', 'MEDIUM', 'LOW')
        tags: Comma-separated list of tags to filter by
        recurrence: Filter by recurrence type ('NONE', 'DAILY', 'WEEKLY', 'MONTHLY')
        sort_by: Sort by field ('priority', 'due_date', 'created_at', 'description', 'id')
        order: Sort order ('asc' or 'desc')
        limit: Number of results to return
        offset: Number of results to skip

    Returns:
        List of todo dictionaries with all fields (filtered by user_id)

    Business Rules:
        - Returns only todos belonging to authenticated user
        - Supports optional filtering by search term, status, priority, tags, and recurrence
        - Supports optional sorting by various fields
        - Supports optional pagination with limit and offset
        - Other users' todos are not visible
    """
    try:
        # Build query with user filter
        query = select(Todo).where(Todo.user_id == user_id)

        # Apply search filter (description contains keyword)
        # For better performance with large datasets, use PostgreSQL full-text search
        if search:
            # Using PostgreSQL's full-text search for better performance with large datasets
            # This approach is more efficient than ilike for large collections
            from sqlalchemy import text
            # Use parameterized query to prevent SQL injection
            query = query.where(text("to_tsvector('english', description) @@ plainto_tsquery('english', :search)")).params(search=search)

        # Apply status filter
        if status:
            if status.lower() == 'completed':
                query = query.where(Todo.completed == True)
            elif status.lower() == 'incomplete':
                query = query.where(Todo.completed == False)

        # Apply priority filter
        if priority:
            try:
                priority_enum = PriorityEnum[priority.upper()]
                query = query.where(Todo.priority == priority_enum)
            except KeyError:
                raise HTTPException(status_code=400, detail=f"Invalid priority: {priority}")

        # Apply tags filter
        if tags:
            tag_list = tags.split(',')
            for tag in tag_list:
                tag = tag.strip()
                # For JSON array, use contains to check if the tag exists in the tags array
                query = query.where(Todo.tags.contains([tag]))

        # Apply recurrence filter
        if recurrence:
            try:
                recurrence_enum = RecurrenceEnum[recurrence.upper()]
                query = query.where(Todo.recurrence_type == recurrence_enum)
            except KeyError:
                raise HTTPException(status_code=400, detail=f"Invalid recurrence type: {recurrence}")

        # Apply sorting
        if sort_by:
            if sort_by == 'priority':
                order_field = Todo.priority
            elif sort_by == 'due_date':
                order_field = Todo.due_date
            elif sort_by == 'created_at':
                order_field = Todo.created_at
            elif sort_by == 'description':
                order_field = Todo.description
            elif sort_by == 'id':
                order_field = Todo.id
            else:
                # Default to id if sort_by is invalid
                order_field = Todo.id

            # Apply sort order
            if order and order.lower() == 'desc':
                query = query.order_by(order_field.desc())
            else:
                query = query.order_by(order_field.asc())
        else:
            # Default sorting
            query = query.order_by(Todo.id)

        # Apply limit and offset for pagination
        if limit is not None:
            query = query.limit(limit)
        if offset is not None:
            query = query.offset(offset)

        result = await db.execute(query)
        todos = result.scalars().all()

        return [
            {
                "id": todo.id,
                "description": todo.description,
                "completed": todo.completed,
                "priority": todo.priority,
                "tags": todo.tags,
                "due_date": todo.due_date,
                "recurrence_type": todo.recurrence_type,
                "reminder_time": todo.reminder_time,
                "user_id": todo.user_id,
                "created_at": todo.created_at,
                "updated_at": todo.updated_at
            }
            for todo in todos
        ]
    except HTTPException:
        # Re-raise HTTP exceptions
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to list todos: {str(e)}")


async def get_todo(todo_id: int, user_id: int, db: AsyncSession) -> Dict:
    """
    Get a specific todo by ID from the database with ownership verification

    Args:
        todo_id: The ID of the todo to retrieve
        user_id: ID of the authenticated user
        db: Async database session

    Returns:
        Dict containing the todo data

    Raises:
        HTTPException: 404 if todo not found
        HTTPException: 403 if todo belongs to different user
        HTTPException: 500 if database error occurs

    Business Rules:
        - Returns single todo if found and owned by user
        - Raises 404 if todo does not exist
        - Raises 403 if user doesn't own the todo
    """
    try:
        result = await db.execute(select(Todo).where(Todo.id == todo_id))
        todo = result.scalar_one_or_none()

        if todo is None:
            raise HTTPException(status_code=404, detail=f"Todo {todo_id} not found")

        # Verify ownership
        if todo.user_id != user_id:
            raise HTTPException(status_code=403, detail="Access denied")

        return {
            "id": todo.id,
            "description": todo.description,
            "completed": todo.completed,
            "priority": todo.priority,
            "tags": todo.tags,
            "due_date": todo.due_date,
            "recurrence_type": todo.recurrence_type,
            "reminder_time": todo.reminder_time,
            "user_id": todo.user_id,
            "created_at": todo.created_at,
            "updated_at": todo.updated_at
        }
    except HTTPException:
        raise  # Re-raise 404/403
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to get todo: {str(e)}")




async def delete_todo(todo_id: int, user_id: int, db: AsyncSession) -> None:
    """
    Delete a todo permanently with ownership verification

    Args:
        todo_id: The ID of the todo to delete
        user_id: ID of the authenticated user
        db: Async database session

    Raises:
        HTTPException: 404 if todo not found
        HTTPException: 403 if todo belongs to different user
        HTTPException: 500 if database error occurs

    Business Rules:
        - User must own the todo to delete it
        - Todo is permanently removed (no soft delete)
        - Subsequent operations on deleted ID return 404
        - Transaction committed on success, rolled back on error
    """
    try:
        result = await db.execute(select(Todo).where(Todo.id == todo_id))
        todo = result.scalar_one_or_none()

        if todo is None:
            raise HTTPException(status_code=404, detail=f"Todo {todo_id} not found")

        # Verify ownership
        if todo.user_id != user_id:
            raise HTTPException(status_code=403, detail="Access denied")

        await db.delete(todo)
        await db.commit()

        return None
    except HTTPException:
        raise  # Re-raise 404/403
    except Exception as e:
        await db.rollback()
        raise HTTPException(status_code=500, detail=f"Failed to delete todo: {str(e)}")


async def update_todo(
    todo_id: int,
    user_id: int,
    db: AsyncSession,
    description: Optional[str] = None,
    completed: Optional[bool] = None,
    priority: Optional[PriorityEnum] = None,
    tags: Optional[List[str]] = None,
    due_date: Optional[Union[str, datetime]] = None,
    recurrence_type: Optional[RecurrenceEnum] = None,
    reminder_time: Optional[Union[int, str]] = None
) -> Dict:
    """
    Update a todo's fields with ownership verification

    Args:
        todo_id: The ID of the todo to update
        user_id: ID of the authenticated user
        db: Async database session
        description: New description (optional)
        completed: New completion status (optional)
        priority: New priority level (optional)
        tags: New tags array (optional)
        due_date: New due date (optional, ISO 8601 format string)
        recurrence_type: New recurrence type (optional)
        reminder_time: New reminder time (optional)

    Returns:
        Dict containing the updated todo with all fields

    Raises:
        HTTPException: 404 if todo not found
        HTTPException: 403 if todo belongs to different user
        HTTPException: 500 if database error occurs

    Business Rules:
        - User must own the todo to update it
        - updated_at timestamp is refreshed by database automatically
        - At least one field should be provided for update
        - Partial updates are supported
        - If completing a recurring task, creates the next instance with updated due date
        - Transaction committed on success, rolled back on error
    """
    try:
        result = await db.execute(select(Todo).where(Todo.id == todo_id))
        todo = result.scalar_one_or_none()

        if todo is None:
            raise HTTPException(status_code=404, detail=f"Todo {todo_id} not found")

        # Verify ownership
        if todo.user_id != user_id:
            raise HTTPException(status_code=403, detail="Access denied")

        # Check if we're marking this as completed and it's a recurring task
        was_completed = todo.completed
        will_be_completed = completed if completed is not None else todo.completed

        # Update fields if provided
        if description is not None:
            todo.description = description
        if completed is not None:
            todo.completed = completed
        if priority is not None:
            todo.priority = priority
        if tags is not None:
            todo.tags = tags
        if due_date is not None:
            if isinstance(due_date, str):
                if due_date:  # Only update if not empty string
                    # Parse the ISO 8601 date string with proper timezone handling
                    try:
                        # Handle different ISO 8601 formats that may come from the frontend
                        date_str = due_date.strip()

                        # Handle 'Z' suffix (UTC timezone) by replacing with '+00:00'
                        if date_str.endswith('Z'):
                            date_str = date_str[:-1] + '+00:00'

                        # Handle the 'T' separator for datetime format
                        if 'T' in date_str:
                            # Replace 'T' with ' ' for fromisoformat compatibility
                            date_str = date_str.replace('T', ' ')

                        # Parse the datetime string
                        parsed_date = datetime.fromisoformat(date_str)
                        todo.due_date = parsed_date
                    except ValueError as e:
                        raise HTTPException(status_code=400, detail=f"Invalid due_date format. Use ISO 8601 format (e.g., 2023-12-31T18:00:00 or 2023-12-31 18:00:00). Error: {str(e)}")
                else:
                    # Set to None if empty string is passed
                    todo.due_date = None
            elif isinstance(due_date, datetime):
                # If it's already a datetime object (from Pydantic model), use it directly
                todo.due_date = due_date
            else:
                # If it's neither a string nor datetime, set to None
                todo.due_date = None
        if recurrence_type is not None:
            todo.recurrence_type = recurrence_type
        if reminder_time is not None:
            if isinstance(reminder_time, str):
                if reminder_time == "":
                    # Set to default if empty string is passed
                    todo.reminder_time = 10
                else:
                    try:
                        todo.reminder_time = int(reminder_time)
                    except ValueError:
                        raise HTTPException(status_code=400, detail="Invalid reminder_time format. Must be a number.")
            else:
                # It's already an int
                todo.reminder_time = int(reminder_time)

        await db.commit()
        await db.refresh(todo)

        # If the task was marked as completed and it's a recurring task, create the next instance
        if not was_completed and will_be_completed and todo.recurrence_type != RecurrenceEnum.NONE:
            # Calculate next due date based on recurrence pattern for the new instance
            from datetime import datetime, timedelta
            next_due_date = None

            if todo.due_date:
                current_due_date = todo.due_date

                if todo.recurrence_type == RecurrenceEnum.DAILY:
                    next_due_date = current_due_date + timedelta(days=1)
                elif todo.recurrence_type == RecurrenceEnum.WEEKLY:
                    next_due_date = current_due_date + timedelta(weeks=1)
                elif todo.recurrence_type == RecurrenceEnum.MONTHLY:
                    # Calculate next month (handle month overflow)
                    year = current_due_date.year
                    month = current_due_date.month + 1

                    if month > 12:
                        year += 1
                        month = 1

                    # Handle day overflow (e.g., Jan 31 + 1 month should be Feb 28/29, not Mar 3)
                    day = min(current_due_date.day, 28)  # Use 28 to avoid month overflow issues

                    next_due_date = current_due_date.replace(year=year, month=month, day=day)

            # Create a new todo with the same properties but reset completion status
            new_todo_data = {
                "description": todo.description,
                "user_id": todo.user_id,
                "completed": False,  # New recurring task starts as incomplete
                "priority": todo.priority,
                "tags": todo.tags,
                "due_date": next_due_date,
                "recurrence_type": todo.recurrence_type,
                "reminder_time": int(todo.reminder_time) if todo.reminder_time is not None else 10,
            }

            new_todo = Todo(**new_todo_data)
            db.add(new_todo)
            await db.commit()

        return {
            "id": todo.id,
            "description": todo.description,
            "completed": todo.completed,
            "priority": todo.priority,
            "tags": todo.tags,
            "due_date": todo.due_date,
            "recurrence_type": todo.recurrence_type,
            "reminder_time": todo.reminder_time,
            "user_id": todo.user_id,
            "created_at": todo.created_at,
            "updated_at": todo.updated_at
        }
    except HTTPException:
        raise  # Re-raise 404/403
    except Exception as e:
        await db.rollback()
        raise HTTPException(status_code=500, detail=f"Failed to update todo: {str(e)}")