using Microsoft.AspNet.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using survey_beta.DTOs.Create;
using survey_beta.DTOs.Response;
using survey_beta.DTOs.Update;
using survey_beta.Models;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

[Route("api/[controller]")]
[ApiController]
public class SurveyController : ControllerBase
{
    private readonly SurveyService _surveyService;
    private readonly Microsoft.AspNetCore.Identity.UserManager<User> _userManager;

    public SurveyController(SurveyService surveyService, Microsoft.AspNetCore.Identity.UserManager<User> userManager)
    {
        _surveyService = surveyService;
        _userManager = userManager;
    }

    [HttpGet("GetAll&ById")]
    public async Task<IActionResult> GetAllSurveys([FromQuery] string id = null)
    {
        var surveys = await _surveyService.GetAllSurveysAsync(id);
        return Ok(surveys);
    }
    [HttpPost("Create-Survey")]
   // [Authorize]
    public async Task<IActionResult> CreateSurvey([FromBody] CreateSurveyDto request)
    {
        var userId = _userManager.GetUserId(User);
        var survey = await _surveyService.CreateSurveyAsync(request, userId);
        return Ok(survey);
    }
    //[Authorize]
    [HttpPut("EditSurvey/{id}")]
    public async Task<IActionResult> UpdateSurvey([FromBody] UpdateSurveyDto request)
    {
        try
        {
            var success = await _surveyService.UpdateSurveyAsync(request);
            if (!success) return NotFound(new { message = "Survey not found." });

            return NoContent();
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
        catch (Exception)
        {
            return StatusCode(500, new { message = "An unexpected error occurred." });
        }
    }
    //[Authorize]
    [HttpPatch("publish-Survey/{id}")]
    public async Task<IActionResult> PublishSurvey(string id)
    {
        var success = await _surveyService.PublishSurveyAsync(id);
        if (!success) return NotFound(new { message = "Survey not found." });
        return Accepted(new { message = "Survey has been published." });
    }

    //[Authorize]
    [HttpPatch("unpublish-Survey/{id}")]
    public async Task<IActionResult> UnpublishSurvey(string id)
    {
        var success = await _surveyService.UnpublishSurveyAsync(id);
        if (!success) return NotFound(new { message = "Survey not found." });
        return Accepted(new { message = "Survey has been unpublished." });
    }

    //[Authorize]
    [HttpDelete("Delete-Survey{id}")]
    public async Task<IActionResult> DeleteSurvey(string id)
    {
        var success = await _surveyService.DeleteSurveyAsync(id);
        if (!success) return NotFound(new { message = "Survey not found." });
        return Accepted(new { message = "Survey has been Removed." });
    }
}
