import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import { authAPI } from '../services/authAPI';

// API Response Types
interface LoginSuccessResponse {
  status: 'success';
  message: string;
  data: {
    accessToken: string;
    refreshToken: string;
    user: AuthUser;
  };
  timestamp: string;
}

interface LoginErrorResponse {
  status: 'error';
  message: string;
  errorCode: string;
  timestamp: string;
}

type LoginResponse = LoginSuccessResponse | LoginErrorResponse;

export interface AuthUser {
  id: number;
  uuid: string;
  email: string;
  displayName: string;
  role: string;
}

export interface AuthState {
  user: AuthUser | null;
  accessToken: string | null;
  refreshToken: string | null;
  loading: boolean;
  error: string | null;
  isAuthenticated: boolean;
}

const initialState: AuthState = {
  user: null,
  accessToken: null,
  refreshToken: null,
  loading: false,
  error: null,
  isAuthenticated: false,
};

export const login = createAsyncThunk(
  'auth/login',
  async (payload: { email: string; password: string }, { rejectWithValue }) => {
    try {
      const response = await authAPI.login(payload.email, payload.password);
      console.log('login response igot',response)
      const data = response.data as LoginResponse;
      
      if (data.status === 'success') {
        return {
          accessToken: data.data.accessToken,
          refreshToken: data.data.refreshToken,
          user: data.data.user,
        };
      } else {
        return rejectWithValue(data.message || 'Login failed');
      }
    } catch (error: any) {
      // Handle network errors or API errors
      if (error.response?.data?.status === 'error') {
        const errorData = error.response.data as LoginErrorResponse;
        return rejectWithValue(errorData.message || 'Login failed');
      }
      return rejectWithValue(error.message || 'Network error occurred');
    }
  },
);

const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    logout: state => {
      state.user = null;
      state.accessToken = null;
      state.refreshToken = null;
      state.error = null;
      state.isAuthenticated = false;
    },
    clearError: state => {
      state.error = null;
    },
  },
  extraReducers: builder => {
    builder
      .addCase(login.pending, state => {
        state.loading = true;
        state.error = null;
      })
      .addCase(login.fulfilled, (state, action) => {
        state.loading = false;
        state.accessToken = action.payload.accessToken;
        state.refreshToken = action.payload.refreshToken;
        state.user = action.payload.user;
        state.isAuthenticated = true;
        state.error = null;
      })
      .addCase(login.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string || 'Login failed';
        state.isAuthenticated = false;
      });
  },
});

export const { logout, clearError } = authSlice.actions;
export default authSlice;


