import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import type { UserBrief } from "@/api/auth";
import { getToken, setToken, clearToken } from "@/api/client";

interface AuthState {
  token: string | null;
  user: UserBrief | null;
  companyId: string | null; // "std" / "ent" / "trial"
  companyName: string | null;
}

const initialState: AuthState = {
  token: getToken(),
  user: null,
  companyId: null,
  companyName: null,
};

const slice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    loginSucceeded(
      state,
      action: PayloadAction<{
        token: string;
        user: UserBrief;
        companyId: string;
        companyName: string;
      }>
    ) {
      state.token = action.payload.token;
      state.user = action.payload.user;
      state.companyId = action.payload.companyId;
      state.companyName = action.payload.companyName;
      setToken(action.payload.token);
    },
    logout(state) {
      state.token = null;
      state.user = null;
      state.companyId = null;
      state.companyName = null;
      clearToken();
    },
  },
});

export const { loginSucceeded, logout } = slice.actions;
export default slice.reducer;
