<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\TaskActivity;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;

class TaskActivityController extends Controller
{
    /**
     * Store a newly created activity for a task
     */
    public function store(Request $request, $taskId)
    {
        $validator = Validator::make($request->all(), [
            'type' => 'required|in:COMMENT,STATUS_CHANGE,ATTACHMENT',
            'message' => 'nullable|string|max:2000',
            'attachment' => 'nullable|file|max:5120', // 5MB max
            'user_id' => 'required|exists:users,id',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation error',
                'errors' => $validator->errors()
            ], 422);
        }

        try {


            $path = null;
            $name = null;

            if ($request->hasFile('attachment')) {
                $file = $request->file('attachment');
                $name = $file->getClientOriginalName();
                $path = $file->store('task-attachments', 'public');
            }

            $activity = TaskActivity::create([
                'task_id' => $taskId,
                'user_id' => $request->user_id,
                'type' => $request->type,
                'message' => $request->message,
                'attachment_path' => $path,
                'attachment_name' => $name,
            ]);

            // Load user relationship
            $activity->load('user');

            return response()->json([
                'success' => true,
                'message' => 'Activity added successfully',
                'data' => $activity
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to add activity',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get activities for a specific task
     */
    public function index($taskId)
    {
        try {
            $activities = TaskActivity::with('user')
                ->where('task_id', $taskId)
                ->latest()
                ->get();

            return response()->json([
                'success' => true,
                'data' => $activities
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch activities',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Download attachment
     */
    public function downloadAttachment($activityId)
    {
        try {
            $activity = TaskActivity::find($activityId);

            if (!$activity || !$activity->attachment_path) {
                return response()->json([
                    'success' => false,
                    'message' => 'Attachment not found'
                ], 404);
            }

            $path = storage_path('app/public/' . $activity->attachment_path);

            if (!file_exists($path)) {
                return response()->json([
                    'success' => false,
                    'message' => 'File not found'
                ], 404);
            }

            return response()->download($path, $activity->attachment_name);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to download attachment',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
