using Npgsql;
using TravelAgencyWinForms.Data;
using TravelAgencyWinForms.Models;
using TravelAgencyWinForms.Utils;

namespace TravelAgencyWinForms.Services;

public static class AuthService
{
    public static bool Login(string login, string password, out string error)
    {
        error = string.Empty;

        try
        {
            var table = Db.Query(
                "SELECT * FROM fn_authenticate_user(@login, @password);",
                new NpgsqlParameter("login", login.Trim()),
                new NpgsqlParameter("password", password));

            if (table.Rows.Count == 0)
            {
                error = "Неверный логин или пароль, либо учётная запись отключена.";
                return false;
            }

            var row = table.Rows[0];
            CurrentUser.UserId = Convert.ToInt32(row["user_id"]);
            CurrentUser.Login = Convert.ToString(row["login"]) ?? string.Empty;
            CurrentUser.Role = Convert.ToString(row["role"]) ?? string.Empty;

            if (table.Columns.Contains("client_id"))
                CurrentUser.ClientId = row["client_id"] == DBNull.Value ? null : Convert.ToInt32(row["client_id"]);
            else if (table.Columns.Contains("employee_id"))
                CurrentUser.ClientId = row["employee_id"] == DBNull.Value ? null : Convert.ToInt32(row["employee_id"]);
            else
                CurrentUser.ClientId = null;

            if (table.Columns.Contains("client_name"))
            {
                CurrentUser.ClientName = Convert.ToString(row["client_name"]) ?? string.Empty;
            }
            else if (CurrentUser.ClientId != null)
            {
                var clientTable = Db.Query(
                    "SELECT concat_ws(' ', last_name, first_name, middle_name) AS client_name FROM clients WHERE client_id = @client_id;",
                    new NpgsqlParameter("client_id", CurrentUser.ClientId.Value));

                CurrentUser.ClientName = clientTable.Rows.Count > 0
                    ? Convert.ToString(clientTable.Rows[0]["client_name"]) ?? string.Empty
                    : string.Empty;
            }
            else
            {
                CurrentUser.ClientName = string.Empty;
            }

            Db.SetAppContext(CurrentUser.Login);
            return true;
        }
        catch (Exception ex)
        {
            error = "Ошибка авторизации: " + ErrorHelper.ToUserMessage(ex);
            return false;
        }
    }
}
